Do─čukan Uçak Do─čukan Uçak - 1 year ago 94
Python Question

Python Preventing For Each loop to iterate single string by char

I have a variable which can be a single string or a list of string. When the variable is a single string , the loop iterates it by char.

text = function() # the function method can return a single string or list of string
for word in text:
print word+"/n"
# When it is a single string , it prints char by char.

I would want the loop to iterate only one time when it is a single string. I actually do not want to use other loop types. How can I do it with for each structure?

Answer Source

This should do it:

text = function() 
if isinstance(text, list):
    for word in text:
        print word + "/n"
    print text + "/n"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download