简体   繁体   English

如何将列表中的元素转换为一个字符串?

[英]How to transform elements of a list into one string?

community, 社区,

I have a list, that consists of different strings (sentences, words...) I would like to join them all together to one string. 我有一个列表,其中包含不同的字符串(句子,单词...),我想将它们全部组合成一个字符串。 I tried: 我试过了:

kafka = ['Das ist ein schöner Tag.', '>>I would like some ice cream and a big cold orange juice!',...]
''.join(kafka) #but strings stay the same as before

You need to do: 您需要做:

kafka = ['Das ist ein schöner Tag.', '>>I would like some ice cream and a big cold orange juice!',...]
s = ''.join(kafka)

s now contains your concatenated string. s现在包含您的串联字符串。

Basically you are on the right track, but you need to assign the join operation to a new variable or use it directly. 基本上,您处于正确的轨道,但是您需要将联接操作分配给新变量或直接使用它。 the original list won't be affected. 原始列表不会受到影响。

concatenate them with or without any spaces in between: 将它们串联在一起,中间可以有或没有空格:

no_spaces = ''.join(kafka)
with_spaces = ' '.join(kafka)

print no_spaces
print with_spaces

The reason is that 原因是

''.join(kafka)

returns the new string without modifying kafka. 返回新的字符串,而不修改kafka。 Try: 尝试:

my_string = ''.join(kafka)

And if you want spaces between sentences then use: 如果您想在句子之间留空格,请使用:

my_string = ' '.join(kafka)

''.join(kafka) returns a string. ''.join(kafka)返回一个字符串。 To make use of it, store it into a variable: 要使用它,请将其存储到变量中:

joined = ''.join(kafka)
print joined

Note: you may want to join with a space ' ' instead. 注意:您可能想用空格' '代替。

You can join it using , 您可以使用来加入它,

Assuming your list is 假设您的清单是

['Das ist ein schöner Tag.', '>>I would like some ice cream and a big cold orange juice!']

>>> kafka = ['Das ist ein schöner Tag.', '>>I would like some ice cream and a big cold orange juice!']
>>>' '.join(kafka)

Output : 输出:

'Das ist ein sch\xf6ner Tag. >>I would like some ice cream and a big cold orange juice!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM