如何将字符串列表连接为一个字符串?
例如,给定 ['this','is','a','sentence'],我该如何得到 "this-is-a-sentence"?
如果要处理一些分别存储在不同变量中的字符串,请参见如何在Python中将一个字符串附加到另一个字符串上?。
如果需要相反的过程-从一个字符串创建一个列表,请参见如何将字符串拆分成字符列表?或者如何将字符串拆分成单词列表?。
如何将字符串列表连接为一个字符串?
例如,给定 ['this','is','a','sentence'],我该如何得到 "this-is-a-sentence"?
如果要处理一些分别存储在不同变量中的字符串,请参见如何在Python中将一个字符串附加到另一个字符串上?。
如果需要相反的过程-从一个字符串创建一个列表,请参见如何将字符串拆分成字符列表?或者如何将字符串拆分成单词列表?。
使用str.join函数:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
将列表转换为字符串的更通用方法(也适用于数字列表)是:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
map(str, my_lst) 就足够了,不需要枚举列表 =) - alvasint,但它可以是任何可以表示为字符串的类型。 - Aaron S' '.join(map(lambda x: ' $'+ str(x), my_lst))将返回'$1 $2 $3 $4 $5 $6 $7 $8 $9 $10'。 - ScottMcCmap()和lambda。@ScottMcC更新的示例:' '.join(f'${x}' for x in my_lst)的计算结果为:'$1 $2 $3 $4 $5 $6 $7 $8 $9 $10' --- 注意:原始示例中的' $'有不需要的空格。 - pabouk - Ukraine stay strong初学者了解为什么join是字符串方法非常有用。
一开始可能很奇怪,但之后会变得非常有用。
join的结果始终是一个字符串,但要连接的对象可以是许多类型(生成器、列表、元组等)。
.join更快,因为它仅分配一次内存。优于经典串联(详见详细解释)。
一旦你学会了它,就会非常方便,你可以使用类似这样的技巧添加括号。
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
join(),也就是 join(("(",")")) 是干什么的吗?就像魔法一样。 - cryanbhu("(",")")是由两个字符串组成的元组 - 开括号"("和闭括号 ")"。因此,第二个join()方法使用第一个join()方法的输出作为分隔符将这两个字符串连接起来(即'1,2,3,4,5')。 - zepman.join方法连接列表、元组或生成器,它们是不同类型的集合,但它们应该只包含字符串。 - user3064538来自未来的编辑:请不要使用下面的答案。此功能已在Python 3中删除,并且Python 2已经过时。即使您仍在使用Python 2,也应编写适用于Python 3的代码,以便更轻松地进行必要的升级。
尽管@Burhan Khalid的答案很好,但我认为这样更容易理解:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
join()的第二个参数是可选的,默认为“ ”。
>>> list_abc = ['aaa', 'bbb', 'ccc']
>>> string = ''.join(list_abc)
>>> print(string)
aaabbbccc
>>> string = ','.join(list_abc)
>>> print(string)
aaa,bbb,ccc
>>> string = '-'.join(list_abc)
>>> print(string)
aaa-bbb-ccc
>>> string = '\n'.join(list_abc)
>>> print(string)
aaa
bbb
ccc
>>> 作为输出而不是命令非常令人困惑。 - pabouk - Ukraine stay strongreduce函数:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
join 不就好了吗? - Sebastián Palma' '而不是'-':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
>>> aa
[None, 10, 'hello']
将其转换为字符串:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
如果需要,转换回列表:
>>> ast.literal_eval(st)
[None, 10, 'hello']
str(aa)也会返回"[None, 10, 'hello']"... - Tomerikoosentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
sentences_strings = ','.join(f"'{word}'" for word in sentence) 作为一个重要的额外好处,你可以在一个地方将字符串 ' 包围起来,而不是散布在整个表达式中。 - pabouk - Ukraine stay strongstr.format()来通过解包列表内的值将列表中的值按顺序插入占位符中,从而将列表中的值连接起来。它还可以处理非字符串类型的值。
lst1 = ['this', 'is', 'a', 'sentence']
lst2 = ['numbers', 1, 2, 3]
'{}-{}-{}-{}'.format(*lst1) # 'this-is-a-sentence'
'{} {}, {} and {}'.format(*lst2) # 'numbers 1, 2 and 3'
对于一个大列表,我们可以使用列表的长度来初始化相应数量的占位符。有两种方法可以实现这一点:
', '.join(['{}']*len(lst)).format(*lst)
('{}, '*len(lst)).rstrip(', ').format(*lst)
lst = [1.2345, 3.4567, 4.567, 5.6789, 7.8]
', '.join(['{}']*len(lst)).format(*lst) # '1.2345, 3.4567, 4.567, 5.6789, 7.8'
('{}, '*len(lst)).format(*lst).rstrip(', ')
# with a float format specification
', '.join(['{:.2f}']*len(lst)).format(*lst) # '1.23, 3.46, 4.57, 5.68, 7.80'
sentence.join(" ")也能起作用,因为它的反向操作是list.split(" ")。你知道这个功能是否会被添加到Python列表方法中吗? - Wouter Thielenlist.join对于任意列表来说都不合适。另一方面,str.join的参数可以是任何“可迭代”的字符串序列,而不仅仅是一个列表。唯一有意义的是内置函数join(list,sep);如果你真的需要它,在(基本上已过时的)string模块中有一个。 - alexisstr()方法,这将把它转换为字符串表示形式,''.join(map(str, [obj1,obj2,obj3]))。 - Burhan Khalid