如何将一个字符串列表连接成一个字符串?
例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"?
要在单独的变量中处理几个字符串,请参见如何在Python中将一个字符串附加到另一个字符串。
对于相反的过程-从字符串创建列表-请参阅如何将字符串分割为字符列表?或如何将字符串分割成单词列表?是合适的。
如何将一个字符串列表连接成一个字符串?
例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"?
要在单独的变量中处理几个字符串,请参见如何在Python中将一个字符串附加到另一个字符串。
对于相反的过程-从字符串创建列表-请参阅如何将字符串分割为字符列表?或如何将字符串分割成单词列表?是合适的。
当前回答
如果你有一个混合内容列表,想要stringify它,这里有一种方法:
考虑一下这个列表:
>>> 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.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
来自未来的编辑:请不要使用下面的答案。这个函数在python3中被移除,python2已经死亡。即使你仍在使用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
如果你有一个混合内容列表,想要stringify它,这里有一种方法:
考虑一下这个列表:
>>> 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']
一种更通用的方法(也包括数字列表)将列表转换为字符串:
>>> 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