Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing a Python For-loop from iterating over a 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?

like image 732
vvvnn Avatar asked Nov 29 '16 18:11

vvvnn


2 Answers

It would be cleaner if your function would always return a list even one with only one element. I would highly recommend this if you can change your code there.

Otherwise add this line before your loop:

text = text if isinstance(text, list) else [text]

Also your variable names are confusing you should call "text" "word_list" or something just to better indicate the type required.

Requiring type checking usually indicates a problem of style.

like image 155
Falk Schuetzenmeister Avatar answered Nov 06 '22 05:11

Falk Schuetzenmeister


This should do it:

text = function() 
if isinstance(text, list):
    for word in text:
        print word + "/n"
else:
    print text + "/n"
like image 42
Fejs Avatar answered Nov 06 '22 06:11

Fejs