SIRHC SIRHC - 6 months ago 12
Python Question

Adding a space before every other letter in a for loop with a string

I apologize beforehand if this has already been covered, but I've been unable to find an answer.

I want a for loop to produce an output with every other letter having a space before it. Should look something like this:

>>>everyOther('banana')
b
a
n
a
n
a


I understand the general concept of for loops and so far I get how:

def everyOther(word):
for each in word:
print each


produces:

w
o
r
d


but I'm not sure how to select which letters would have a space before it.

Any help or directions would be very helpful. ^o^

Answer

You can use enumerate() to return an incrementing index number for each letter in the string, along with the letter itself.

You can then check to see if the number is divisible by 2, using the modulus operator (remember, they start at 0). If it's not divisible by 2, print the space first to get your desired output.

def everyOther(word):
    for index, letter in enumerate(word):
        if index % 2 == 0:
            print letter
        else:
            print " " + letter

Here's an example:

In [7]: everyOther("bananas")
 b
a
 n
a
 n
a
 s