📜  Python|到 String 的元组列表

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

Python|到 String 的元组列表

很多时候,我们可能会遇到需要在字符串之间执行相互转换的问题,在这些情况下,我们可能会遇到需要将元组列表转换为原始的逗号分隔字符串的问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用str() + strip()
上述功能的组合可以用来解决这个问题。在此,我们只是将一个列表转换为字符串,并去掉列表的左方括号和右方括号以呈现一个字符串。

# Python3 code to demonstrate working of
# List of tuples to String
# using str() + strip()
  
# initialize list
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List of tuples to String
# using str() + strip()
res = str(test_list).strip('[]')
  
# printing result
print("Resultant string from list of tuple : " + res)
输出 :
The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)

方法 #2:使用map() + join()
这是可以执行此任务的另一种方式。在此,我们将字符串转换函数应用于每个元素,然后使用join()连接元组。

# Python3 code to demonstrate working of
# List of tuples to String
# using map() + join()
  
# initialize list
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List of tuples to String
# using map() + join()
res = ", ".join(map(str, test_list))
  
# printing result
print("Resultant string from list of tuple : " + res)
输出 :
The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)