48

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.

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86
  • 3
    Why not show exactly how you "used the string.join() command"? – Karl Knechtel Dec 17 '11 at 20:48
  • I agree with @KarlKnechtel, adding the (minimal) code that leads to the unwanted results, helps a lot. Here I guess, the code was `''.join(['hello', 'good', 'morning'])` – Qaswed Oct 22 '19 at 13:58

5 Answers5

85

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

 ' '.join(list)
Lance Collins
  • 3,365
  • 8
  • 41
  • 56
24
>>> ' '.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.

Rodrigue
  • 3,617
  • 2
  • 37
  • 49
kev
  • 155,172
  • 47
  • 273
  • 272
6

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.

Alexander
  • 105,104
  • 32
  • 201
  • 196
bofh.at
  • 550
  • 3
  • 6
4

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

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
3
>>> " ".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.

example:

>>> import string
>>> string.join(['hello', "good", "morning"])
'hello good morning'
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130