简体   繁体   English

如何将列表中的项目连接到单个字符串?

[英]How do I concatenate items in a list to a single string?

如何将字符串列表连接成单个字符串?

['this', 'is', 'a', 'sentence']    →    'this-is-a-sentence'

Use str.join :使用str.join

>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'

A more generic way to convert python lists to strings would be:将 python 列表转换为字符串的更通用的方法是:

>>> xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ''.join(map(str, xs))
'12345678910'

It's very useful for beginners to know why join is a string method .对于初学者来说知道为什么 join 是一个字符串方法是非常有用的。

It's very strange at the beginning, but very useful after this.一开始很奇怪,但之后非常有用。

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc). join 的结果始终是一个字符串,但要连接的对象可以是多种类型(生成器、列表、元组等)。

.join is faster because it allocates memory only once. .join更快,因为它只分配一次内存。 Better than classical concatenation (see, extended explanation ).比经典串联更好(请参阅扩展解释)。

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.一旦你学会了它,它就会很舒服,你可以做这样的技巧来添加括号。

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

Edit from the future : Please don't use the answer below.从未来编辑:请不要使用下面的答案。 This function was removed in Python 3 and Python 2 is dead.这个函数在 Python 3 中被删除了,Python 2 已经死了。 Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.即使您仍在使用 Python 2,您也应该编写 Python 3 就绪代码,以使不可避免的升级更容易。


Although @Burhan Khalid's answer is good, I think it's more understandable like this:虽然@Burhan Khalid 的回答很好,但我认为这样更容易理解:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ". 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

We can also use Python's reduce function:我们还可以使用 Python 的reduce函数:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

We can specify how we have to join the string.我们可以指定我们必须如何加入字符串。 Instead of '-', we can use ' '代替'-',我们可以使用''

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

If you want to generate a string of strings separated by commas in final result, you can use something like this:如果你想在最终结果中生成一个用逗号分隔的字符串,你可以使用这样的东西:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

If you have mixed content list.如果您有混合内容列表。 And want to stringify it.并想对其进行字符串化。 Here is one way:这是一种方法:

Consider this list:考虑这个列表:

>>> aa
[None, 10, 'hello']

Convert it to string:将其转换为字符串:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

If required, convert back to list:如果需要,转换回列表:

>>> ast.literal_eval(st)
[None, 10, 'hello']
list = [1, "a", 3, "b", 3.14]

list_str = ""

for item in list:
  
    list_str += str(item)

print (list_str)

# > 1a3b3.14
def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)

Without .join() method you can use this method:如果没有 .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']

So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string.因此,在此示例中基于范围的 for 循环,当 python 到达列表的最后一个单词时,它不应该在 concenated_string 中添加“-”。 If its not last word of your string always append "-" string to your concenated_string variable.如果它不是您的字符串的最后一个单词,请始终将“-”字符串附加到您的 concenated_string 变量。

This will help for sure -这肯定会有所帮助-

arr=['a','b','h','i']     # let this be the list
s=""                      # creating a empty string
for i in arr:
   s+=i                   # to form string without using any function
print(s) 


       

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

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