Shiv18
Shiv18

Reputation: 47

How to use this for loop to get expected result in python

a=['hi','helllo']
for i in a:
    for j in i:
         print j

I'm getting output as : h i h e l l o

What i'm expecting is hi hello

Is there anyway to do achieve this ? Thanks in advance!

Upvotes: 0

Views: 47

Answers (1)

mhawke
mhawke

Reputation: 87084

Update

As you insist on using nested for loops, here a way to make that work:

import sys

a = ['hi','helllo']
first = True
for i in a:
    if not first:
        sys.stdout.write(' ')
    first = False
    for j in i:
         sys.stdout.write(j)
print()

This writes each character directly to sys.stdout. It ensures that a space character separates each word, and jumps through some hoops to make sure that there is no trailing space character. It's awful and I can not think of a reason to do it this way.

Here is a much better way to achieve it; use str.join():

>>> a = ['hi','helllo']
>>> print(' '.join(a))
hi helllo

The problem with the way that you are doing it is that the inner for loop iterates over each character contained in the strings in a, printing each on its own line. You could ditch the inner loop and print each string without a new line:

a = ['hi','helllo']
for i in a:
    print i,

The trailing comma on the print statement prevents a new line being printed. N.B. this is a Python 2 only solution. The str.join() method will work in both Python 2 and 3.

In Python 3 you can simply do this:

print(*a)

... and the same code can be made to work in Python 2 if you enable the print() function by adding to the top of your python file:

from __future__ import print_function

Upvotes: 2

Related Questions