1

i have:

letters = ['h','e','l','l','o']

and i need:

'h e l l o'

so I've tried using a for loop as follows:

new_str = ''
for str in letters:
    new_str += str + ' '

however, the result is:

new_str = 'h e l l o '

is there a way to do this without the empty string after the o? as in without doing something after i already get the result.

Sorry i forgot to mention if there's a way to do this by iterating over the list.

Totem
  • 7,189
  • 5
  • 39
  • 66
user3050527
  • 881
  • 1
  • 8
  • 15
  • You have to stop changing your question. It is confusing people. Anyways, what do you mean by "iterating over the list"? Do you mean you have to use a for-loop? –  Dec 09 '13 at 21:29

4 Answers4

9
>>> letters = ['h','e','l','l','o']

>>> mystr = ' '.join(letters)

>>> print mystr

'h e l l o'

That's the simplest, cleanest way, but if you must use a for loop for some reason, you could do the following:

mystr = ''
# this keeps the whole operation within the for loop
for i in range(len(letters)):
    mystr += letters[i] + ' '
    if i == len(letters)-1: # this condition will be tested each iteration, but it seemed more in keeping with your question
        mystr = mystr[:-1] 
Totem
  • 7,189
  • 5
  • 39
  • 66
6

Use str.join:

>>> letters = ['h','e','l','l','o']
>>> " ".join(letters)
'h e l l o'
>>>

Edit:

I think you are saying that you must use a for-loop. If so, you can use this:

>>> letters = ['h','e','l','l','o']
>>> mystr = ""
>>> for letter in letters:
...     mystr += letter + " "
...
>>> mystr.strip()
'h e l l o'

Note however that, if your list contains spaces, you should use slicing at the end instead of str.strip:

>>> mystr[:-1]
'h e l l o'
>>>

That way, you don't remove any spaces on the ends that were supposed to be there.

Community
  • 1
  • 1
1

You could do something like

string = ""
for letter in "hello":
    string += letter + " "

string = string[:-1]

That last line simply removes the trailing whitespace. Read up on slicing here. Alternatively use string = string.strip() which always removes the trailing space in the general case.

If you don't necessarily have to use an explicit loop I'd recommend going with str.join() as demonstrated in the other answers.

Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45
0

Something different, but still not as elegant as simple str.join

>>> print ''.join(reduce(lambda a, b: a + ' ' + b, letters))
smac89
  • 39,374
  • 15
  • 132
  • 179