📌  相关文章
📜  Python – 将列表转换为分隔符分隔的字符串

📅  最后修改于: 2022-05-13 01:54:49.201000             🧑  作者: Mango

Python – 将列表转换为分隔符分隔的字符串

给定元素列表,将其转换为分隔符分隔的字符串。

方法 #1:使用循环 + str()

这是可以执行此任务的方式之一。在此,在将每个元素转换为字符串之后,我们运行一个循环以在每个元素的末尾添加分隔符。

Python3
# Python3 code to demonstrate working of 
# Convert List to delimiter separated String
# Using loop + str()
  
# initializing list
test_list = [7, "Gfg", 8, "is", "best", 9] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing delim 
delim = "*"
  
res = '' 
  
# using loop to add string followed by delim 
for ele in test_list:
    res = res + str(ele) + delim
  
# printing result 
print("The resultant string : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert List to delimiter separated String
# Using join() + str()
  
# initializing list
test_list = [7, "Gfg", 8, "is", "best", 9] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing delim 
delim = "*"
  
# using map to convert each element to string 
temp = list(map(str, test_list))
  
# join() used to join with delimiter
res = delim.join(temp)
  
# printing result 
print("The resultant string : " + str(res))


输出
The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9*

方法 #2:使用 join() + str()

这是可以执行此任务的另一种方式。在此,我们使用 join() 执行通过 delim 连接每个元素的任务,并使用 str() 完成到字符串的转换。

Python3

# Python3 code to demonstrate working of 
# Convert List to delimiter separated String
# Using join() + str()
  
# initializing list
test_list = [7, "Gfg", 8, "is", "best", 9] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing delim 
delim = "*"
  
# using map to convert each element to string 
temp = list(map(str, test_list))
  
# join() used to join with delimiter
res = delim.join(temp)
  
# printing result 
print("The resultant string : " + str(res))
输出
The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9