2016-11-29 148 views
0

我有一個變量,可以是單個字符串或字符串列表。當變量是單個字符串時,循環會通過char來迭代它。Python防止每個循環通過字符遍歷單個字符串

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. 

我想循環迭代只有一次,當它是一個單一的字符串。我其實不想使用其他循環類型。我怎樣才能做到每個結構?

+2

https://stackoverflow.com/questions/2225038/determine-the-type-of-a-python-object這樣? –

+2

檢查'text'類型怎麼樣? – Mohammad

+0

在單個字符串的情況下,您可以將[yourstring]作爲由單個元素組成的列表返回。 – chatton

回答

0

這應做到:

text = function() 
if isinstance(text, list): 
    for word in text: 
     print word + "/n" 
else: 
    print text + "/n" 
+0

這解決了我的問題,謝謝! – vvvnn

0

儘管鴨子打字是常態,但有時您只需檢查某種東西。在這種情況下,您希望實例basestring

text = function() 
if isinstance(text, basestring): 
    print text 
else: 
    for word in text: 
     print word 
+0

'basestring'只有python2 – tacaswell

+0

@tacaswell「python-2.7」標記 – Brian

+0

不會讓我改變我的選票了。最好使用「六」或「餡餅」。 – tacaswell

0

如果你的函數總是返回一個列表,即使只有一個元素的列表,它也會更乾淨。如果你可以在那裏改變你的代碼,我會強烈推薦這個。

你的循環之前,否則加入這一行:

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

而且您的變量名稱混淆,你應該叫「文」「WORD_LIST」什麼的只是爲了更好地說明所需要的類型。

需要類型檢查通常表示樣式問題。

+0

Thx,很明顯,這些列表讓我困惑在這裏:) –

0

您需要isinstance()方法,通過您的變量來檢查值保持的類型,其按文件:

返回true,如果對象參數是CLASSINFO爭論的一個實例,或一個(直接,間接或虛擬)子類。

使用,你可以創建自定義的功能爲:

import collections 

def my_print(my_val): 
    if isinstance(my_val, str): 
     print my_val 
    elif isinstance(my_val, collections.Iterable): # OR, use `list` if you just want check for list object 
     # To check object is iterable^
     for val in my_val: 
      print val 
    else: 
     raise TypeError('Unknown value') 

採樣運行:

>>> my_print('Hello') 
Hello 
>>> my_print(['Hello', 'World']) 
Hello 
World 

instance()檢查是否傳遞的對象是傳遞類與否的實例。

>>> isinstance('hello', str) 
True 
>>> isinstance('hello', list) 
False 

或者,你可以檢查變量的使用type()作爲類型:

>>> type('hello') == str 
True 
+0

這將失敗與'元組' – tacaswell

+0

@tacaswell:感謝您的評論。更新它 –

+0

你只需要特殊情況'str',讓鴨打字照顧其餘的。 – tacaswell

0

由鴨打字還是可行的,你只需要在列表中使用不在字符串中的方法,反之亦然,並捕獲異常,例如copy()是列表方法,但不是str方法。

text = function() 
try: 
    temp_text = text.copy() 
    for word in text: 
     print word 
except AttributeError: 
    print text 

在如果function()返回的字符串text.copy()將上升一個AttributeError例外,不會通過去循環,但去除了塊原樣打印文本,在另一方面,如果text.copy()是上面的代碼這意味着它是一個列表,它繼續到for循環來打印列表中的每個單詞。

+0

你可以檢查屬性而不是實際執行方法:assert(hasattr(text,'copy'))。如果這將是錯誤的,你會得到一個AssertionError。儘管有人說提出異常比類型檢查更好,但哪一個更好。 –