I'm just wondering what do I have to add to the code

print "Hello World"

to output

H e l l o W o r l d

like there's spaces in between each letter?


8 Years
Discussion Span
Last Post by pythopian

You could do:

for c in "Hello World":
    print c ,

In Python2 the comma puts in a space and keeps it on the same line.

Edited by sneekula: n/a


You could also try some string formatting. Check this out...

text = 'Hello World'
for x in text:
    print x.rjust(2)

# output is  H  e  l  l  o     W  o  r  l  d

They're all trying to just confuse you.

print "H e l l o W o r l d"

Edited by AutoPython: n/a


Well I assumed that the poster already knew that way to do it. Here's another way to do it. In all of the solutions except AutoPython's the output will contain three spaces in the middle, but the original post only has one space between the o and the w. Here is a way to do that programatically

mystring = 'Hello World'
outstring = ''

for x in mystring:
   outstring += x
   if x != ' ':
      outstring += ' '
print outstring

I think Pythopian gets the award for most elegant code. That is just beautiful.

Edited by mn_kthompson: n/a


Actually, if you temporarily flip to Reply with quote in the OP post you find out the request was for:

H e l l o  W o r l d

That is 2 spaces between 'o' and 'W', DaniWeb swallowed up the extra space since it was not in a code field. So the honor goes to mn_kthompson!

Edited by vegaseat: n/a


... between "H e l l o" and "W o r l d":

print ' '.join(c if c != ' ' else '' for c in 'Hello World')

To ensure exactly one space everywhere:

print ' '.join(c for c in 'Hello World' if c != ' ')

Edited by pythopian: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.