2017-02-24 71 views
1

我試圖檢查變量數據是字符串型還是整數型,以便我可以處理它。如果以上都不是它應該返回false。我試圖使用isinstance,但它要求數據是兩種類型,這是不可能的。任何更好的方法呢? 這裏是我的代碼:檢查varible是字符串還是int

 if isinstance(data(int, str)): 
     return True 
    else: 
     return false 
+0

的可能的複製[什麼是您在Python類型的典型方法是什麼?(http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in -python) –

+4

[如何檢查一個變量是一個整數還是一個字符串?]可能的重複(http://stackoverflow.com/questions/16488278/how-to-check-if-a-variable-is-an -integer-a-string) –

+0

[Python:檢查變量類型]的可能的重複(http://stackoverflow.com/questions/20704455/python-checking-type-of-variables) – WhatsThePoint

回答

3

由於事實上,你可以使用一個類的元組的第二個參數來isinstance

isinstance(var,(list,int)) 

isinstance(對象,CLASSINFO)

如果CLASSINFO是類別或類型的對象的元組(或遞歸, 其它這樣的元組),如果對象是任何一個實例返回true 類或類型。如果classinfo不是類,類型或元組的類,類型和這些元組,則會引發TypeError異常。

+0

,這似乎是我做的,但它並沒有在我的結尾工作 – Nix

+0

@Nix。檢查你的代碼.'isinstance(data(int,str))'你錯過了一個逗號。而'isinstance'方法絕對可以做到這一點。 – McGrady

+0

我錯過了。非常感謝 – Nix

3

您可以使用布爾or

>>> isinstance(3,int) or isinstance(3,str) 
True 
>>> isinstance("3",int) or isinstance("3",str) 
True 
>>> isinstance([3],int) or isinstance([3],str) 
False 

或指定可能的類型的元組:

>>> isinstance(3, (int, str)) 
True 
>>> isinstance("3", (int, str)) 
True 
>>> isinstance([3], (int, str)) 
False 

所以你的情況,也不會成爲:

isinstance(data(int, str)) 

isinstance(data, (int, str)) 
+0

我明白這一點。有條件的'或'將爲我節省 – Nix

1

您可以使用isinstance(object,classinfo)內置函數。

This應該做的工作

def isStrOrInt(myVar): 
    return isinstance(myVar,int) or isinstance(myVar,str) 


print(isStrOrInt(5)) # True 
print(isStrOrInt('5')) # True 
print(isStrOrInt([])) # False 
print(isStrOrInt('Dinosaurs are Awesome!')) # True 
print(isStrOrInt(3.141592653589793238462)) # False (Because it's a decimal not an int) 

下面是運行版本:https://repl.it/Fw63/1


這就是documentation說:

返回true,如果對象參數是一個classinfo 參數的實例,或(直接,間接或虛擬)的子類。如果 對象不是給定類型的對象,則函數始終返回 false。如果classinfo是類型對象的元組(或遞歸地,其他 這樣的元組),如果object是 類型中的任何一個的實例,則返回true。如果classinfo不是類型和這種元組的類型或元組,則會引發TypeError異常。

基本上,isinstance需要兩個參數,第一是要檢查該變量,第二是要檢查它是否是一個實例(在你的情況intstr數據類型/類)。 This tutorial解釋得很好。

+0

非常感謝。隨着你的解釋,這意味着我的代碼幾乎是正確的。數據「isinstance(data,(int,str))」像@Eric所解釋的那樣缺少什麼。我真的很感激 – Nix