如何将字符串列表连接成单个字符串?
例如,给定
['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
对于初学者来说非常有用 为什么 join 是字符串方法.
一开始很奇怪,但之后就非常有用了。
连接的结果始终是一个字符串,但要连接的对象可以是多种类型(生成器、列表、元组等)。
.join
速度更快,因为它只分配一次内存。比经典串联更好(请参阅扩展解释)。
一旦你学会了,它会非常舒服,你可以做这样的技巧来添加括号。
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
未来编辑:请不要使用下面的答案。这个函数在 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
我们还可以使用Python的
reduce
函数:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
我们可以指定如何连接字符串。我们可以使用
'-'
代替 ' '
:
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']
如果你想在最终结果中生成一串用逗号分隔的字符串,你可以使用这样的东西:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
如果没有 .join() 方法,您可以使用此方法:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
因此,在本例中基于范围的 for 循环,当 python 到达列表的最后一个单词时,它不应该向 concenated_string 添加“-”。如果它不是字符串的最后一个单词,请始终将“-”字符串附加到 concenated_string 变量中。