防止Python For循环通过char迭代单个字符串

vvv*_*vnn 4 python string for-loop python-2.7

我有一个变量,可以是单个字符串或字符串列表.当变量是单个字符串时,循环按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.
Run Code Online (Sandbox Code Playgroud)

我希望循环只在一个字符串时迭代一次.我实际上不想使用其他循环类型.我怎样才能为每个结构做到这一点?

Fal*_*ter 6

如果你的函数总是返回一个列表,即使只有一个元素,也会更清晰.如果您可以在那里更改代码,我强烈推荐这个.

否则在循环之前添加此行:

text = text if isinstance(text, list) else [text]
Run Code Online (Sandbox Code Playgroud)

此外,您的变量名称令人困惑,您应该调用"text""word_list"或其他东西只是为了更好地指出所需的类型.

要求类型检查通常表示风格问题.