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?


Recommended Answers

All 8 Replies

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.

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"

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
print ' '.join(list('Hello World'))

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

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!

... 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 != ' ')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.