Python concat string with list


I wanted to build a string from a list.

I used the string.join() command, but if I have :

['hello', 'good', 'morning']

I get : hellogoodmorning

Is there a method that allows me to put a space between every word ? (without the need to write a for loop)

kind regards.

Asked By: Lucas Kauffman



>>> ' '.join(['hello', 'good', 'morning'])
'hello good morning'

The standard and best way to join a list of strings. I cannot think of anything better than this one.

Answered By: kev
>>> " ".join(['hello', "good", "morning"])
'hello good morning'

or you can use the string.join() function, which uses a single space as the default separator.

>>> help(string.join)
Help on function join in module string:

join(words, sep=' ')
    join(list [,sep]) -> string

    Return a string composed of the words in list, with
    intervening occurrences of sep.  The default separator is a
    single space.


>>> import string
>>> string.join(['hello', "good", "morning"])
'hello good morning'
Answered By: Fredrik Pihl

This does what you want:

" ".join(['hello', 'good', 'morning'])

Generally, when you are calling join() on some string you use " " to specify the separator between the list elements.

Answered By:

All you need to do is add the space in front of join.

 ' '.join(list)
Answered By: Lance Collins

' '.join(...) is the easiest way as others have mentioned. And in fact it is the preferred way to do this in all cases (even if you are joining with no padding, just use ''.join(...)).

While it still has some useful functions… most of the string modules functions have been made methods on the str type/object.

You can find the full list of deprecated string-functions (including join) in the Deprecated string functions section of the python docs.

Answered By: Adam Wagner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.