1127

How do I concatenate a list of strings into a single string?

For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?


For handling a few strings in separate variables, see How do I append one string to another in Python?.

For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
alvas
  • 115,346
  • 109
  • 446
  • 738

11 Answers11

1935

Use str.join:

>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 21
    Didn't understand, what's the '-' on the left supposed to be?? – Lawrence DeSouza Apr 02 '14 at 23:46
  • 11
    @LawrenceDeSouza The string you want to be joined; see the [documentation](https://docs.python.org/2/library/stdtypes.html#string-methods), or [this answer](http://stackoverflow.com/questions/1876191/explain-python-join) which goes into a bit more detail. – Burhan Khalid Apr 06 '14 at 06:53
  • 17
    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
  • 17
    @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 07 '15 at 22:28
  • 1
    @alexis That indeed makes sense, that a Python list can contain elements of mixed types, and that it is not always join-able. Thanks! – Wouter Thielen Sep 12 '15 at 07:09
  • What if we want Output as `this is a sentence` .? – Hayat May 07 '18 at 06:05
  • 1
    To summarize the comments, for those of us who just want to join the strings, the right command is then `''.join(sentence)` on an empty string (see @6pack kid's answer below). – Dr_Zaszuś Apr 16 '20 at 07:30
  • What if one of the item is in another type how can I handle it? – alper Jul 07 '20 at 11:07
  • What if its a list like `['TEST ID', BATCHID', 'TEST2']` and I ONLY want to join `ADD ID` to one string? Output should be `['TESTID', BATCHID', 'TEST2']`. – ericOnline Jan 07 '21 at 01:15
  • what if the elements of the list were custom class objects and not strings ? – Raghav Nov 02 '21 at 22:57
  • 2
    @Raghav you would have to call the `str()` method on the object, and that would convert it to the its string representation, `''.join(map(str, [obj1,obj2,obj3]))` – Burhan Khalid Dec 15 '21 at 07:26
252

A more generic way (covering also lists of numbers) to convert a list to a string 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
mirekphd
  • 4,799
  • 3
  • 38
  • 59
Aaron S
  • 5,023
  • 4
  • 29
  • 30
  • 3
    why is list comprehension necessary when the input is string? also `map(str, my_lst)` would be enough without enumerating the list =) – alvas Dec 01 '15 at 08:58
  • 22
    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 02 '15 at 01:02
  • 5
    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 03:17
  • 4
    adding a map actually helps with datatypes apart from string. Great! – appleboy Feb 28 '19 at 07:55
  • In Python it is preferred to use generator expressions instead of `map()` and `lambda`. Updated example by @ScottMcC: `' '.join(f'${x}' for x in my_lst)` evaluates to: `'$1 $2 $3 $4 $5 $6 $7 $8 $9 $10'` --- Note: The original example has unwanted space in `' $'` – pabouk - Ukraine stay strong Jul 15 '23 at 06:02
64

It's very useful for beginners to know 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(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
heilala
  • 770
  • 8
  • 19
Wallebot
  • 767
  • 5
  • 8
  • 3
    can someone explain what the second `join()` i.e. `join(("(",")"))` does? its like magic – cryanbhu Nov 12 '20 at 07:17
  • 5
    `("(",")")` is a tuple of two strings - the open parenthesis `"("` and the close parenthesis `")"`. So the second `join()` joins those two strings using the output of the first `join()` as the separator (i.e., `'1,2,3,4,5'`). – zepman Feb 18 '21 at 16:47
  • Is this correct? "The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc)." The answer by Aaron S suggests that this is not true, you have to use map(str, ) if there are other types in the list. – O'Rooney Mar 28 '22 at 21:42
  • 1
    @O'Rooney the answer is saying you can `.join` lists, tuples or generators, which are different types of collection, but they should only contain strings. – Boris Verkhovskiy Aug 16 '22 at 18:12
  • Okay voting this up because it is cute as eff, but seriously don't do this for code you want humans to understand. I concede it may be useful for code golf or evil. – Bob Stein Jun 29 '23 at 19:59
18

Edit from the future: Please don't use the answer below. 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 " ".

Anupam
  • 14,950
  • 19
  • 67
  • 94
SilentVoid
  • 502
  • 5
  • 10
  • 23
    [This function is deprecated in 2.x and going to be removed in 3.x.](https://docs.python.org/2/library/string.html#deprecated-string-functions) 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
  • 3
    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
  • 2
    It's scary that I still get up-votes on this. Seriously, use python 3. – SilentVoid Nov 23 '22 at 14:01
17
>>> 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
mounirboulwafa
  • 1,587
  • 17
  • 18
9

We can also use Python's reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Nishkarsh Dixit
  • 137
  • 1
  • 10
9

We can specify how we join the string. Instead of '-', we can use ' ':

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Abhishek V
  • 141
  • 1
  • 7
2

If you have a 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 the list:

>>> ast.literal_eval(st)
[None, 10, 'hello']
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
wiredcontrol
  • 138
  • 8
1

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'"
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Carmoreno
  • 1,271
  • 17
  • 29
  • It works but this code better follows the logic of things: `sentences_strings = ','.join(f"'{word}'" for word in sentence)` As an important bonus you have the characters to enclose the strings `'` in one place, not scattered over the whole expression. – pabouk - Ukraine stay strong Jul 15 '23 at 06:21
0
def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Pyte
  • 19
  • 2
  • 4
    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 07 '20 at 21:58
-1

Without .join() method you can use this method:

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