Joel WInterton Joel WInterton - 2 days ago 6
Python Question

for var in string returning all vars in string Python

My code:

text="Qmfbtf fbu nf"
for f in text:
print "f"


In an ideal situation the output would print 4 f's
However it is returning one f per character in the string.
It seems to be using my statement as for string in text.
How do I get it to execute per "f" in string?

Answer

The f in for f in text: is a variable name; you could have named it anything else and the loop would not have changed. This would be the same:

for character in text:

because that's exactly what the loop does; iterate over every character in the string text.

You'd have to test if that character is the letter f:

for character in text:
    if character == 'f':
        print 'f'

You could also use the str.count() method to count how many times f appears:

print 'f\n' * text.count('f')

This prints f plus a newline, as many times as there are 'f' letters in your input text.

Comments