添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str
                @LawrenceDeSouza The string you want to be joined; see the documentation, or this answer which goes into a bit more detail.
– Burhan Khalid
                Apr 6 '14 at 6:53
                I kind of expected sentence.join(" ") to work as well, since the reverse operation is list.split(" "). Any idea if this is going to be added to Python's methods for lists?
– Wouter Thielen
                Aug 23 '15 at 10:02
                @Wouter, it will not. On the one hand, only lists of strings can be joined; so list.join would be inappropriate for an arbitrary list. On the other, the argument of str.join can be any "iterable" sequence of strings, not just a list. The only thing that would make sense is a built-in function join(list, sep); there's one in the (basically obsolete) string module if you really want it.
– alexis
                Sep 7 '15 at 22:28

A more generic way to convert python lists to strings would be:

>>> 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'
                why is list comprehension necessary when the input is string? also map(str, my_lst) would be enough without enumerating the list =)
– alvas
                Dec 1 '15 at 8:58
                Most of the answers to this question are considering the case when the list has strings in it. Mine is a generic way to convert lists to strings. In my example, the list is of type int but it could be any type that can be represented as a string.
– Aaron S
                Dec 2 '15 at 1:02
                To add to this, map would also be useful when used with a lambda function.  For example ' '.join(map(lambda x: ' $'+ str(x), my_lst)) would return '$1 $2 $3 $4 $5 $6 $7 $8 $9 $10'
– ScottMcC
                Jun 22 '17 at 3:17
why join is a string method.

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 is faster because it allocates memory only once. 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(("(",")"))
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
'(1,2,3,4,5)'
                can someone explain what the second join() i.e. join(("(",")")) does? its like magic
– cryanbhu
                Nov 12 '20 at 7:17

Edit from the future: Please don't use this, this function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.

Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

This function is deprecated in 2.x and going to be removed in 3.x. That being the case, I wouldn't recommend using this over the other answer provided. – Matthew Green Nov 19 '15 at 20:28 @Mathew Green this answer and Burhan Khalid's answer use the same function in different ways, so his answer is deprecated as well. But thanks for pointing that out, gota figure out how to join in 3.x. But if you're using 2.x, it's not going away. – SilentVoid Nov 20 '15 at 21:42 His isn't deprecated though. Your recommendation uses a function from Lib/string.py which is wholly different and deprecated whereas @BurhanKhalid answer uses the built-in string method which is not deprecated. His answer is the most correct one now and going forward whereas this is only good for now on 2.x. – Matthew Green Nov 20 '15 at 22:07 All that to say that if you want to promote this alternative you should also include a warning that this is not recommended for the reasons outlined in my previous comments. – Matthew Green Nov 20 '15 at 22:12

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)
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

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) 

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'"

I hope this can help someone.

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. If its not last word of your string always append "-" string to your concenated_string variable.

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – alan.elkin May 7 '20 at 21:58

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.