使用 str.join() 方法将列表转换为逗号分隔的字符串,例如 my_str = ','.join(my_list)。 str.join()

# ✅ Convert list of strings to comma-separated string
# ✅ 将字符串列表转换为逗号分隔的字符串

list_of_strings = ['one', 'two', 'three']

my_str = ','.join(list_of_strings)
print(my_str)  # 👉️ one,two,three

 # --------------------------------

# ✅ Convert list of integers to comma-separated string
# ✅ 将整数列表转换为逗号分隔的字符串

list_of_integers = [1, 3, 5, 7]

my_str = ','.join(str(item) for item in list_of_integers)
print(my_str)  # 👉️ 1,3,5,7

  

我们使用 str.join()

str.join

请注意 ,如果可迭代对象中有任何非字符串值,该方法会引发 TypeError

如果我们的列表包含数字或其他类型,请在调用 join()

list_of_integers = [1, 3, 5, 7]

my_str = ','.join(str(item) for item in list_of_integers)
print(my_str)  # 👉️ 1,3,5,7

str()

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

调用 join()

list_of_strings = ['one', 'two', 'three']

my_str = ','.join(list_of_strings)
print(my_str)  # 👉️ one,two,three

  

如果我们不需要分隔符而只想将列表的元素连接到一个字符串中,请对空字符串调用 join()

list_of_strings = ['one', 'two', 'three']

my_str = ''.join(list_of_strings)
print(my_str)  # 👉️ onetwothree

  

如果需要使用空格分隔符连接列表的元素,请对包含空格的字符串调用 join()

list_of_strings = ['one', 'two', 'three']

my_str = ' '.join(list_of_strings)
print(my_str)  # 👉️ one two three

  

我们还可以在调用 join() 之前使用 map()

list_of_integers = [1, 3, 5, 7]

my_str = ','.join(map(str, list_of_integers))
print(my_str)  # 👉️ 1,3,5,7

  

map()

使用列表中的每个数字调用 str()