Is er een manier om te controleren of het type variabele in python een string
is, zoals:
isinstance(x,int);
voor gehele waarden?
Antwoord 1, autoriteit 100%
In Python 2.x zou je dat doen
isinstance(s, basestring)
basestring
is de abstracte superklassevan str
en unicode
. Het kan worden gebruikt om te testen of een object een instantie is van str
of unicode
.
In Python 3.x is de juiste test
isinstance(s, str)
De klasse bytes
wordt niet beschouwd als een tekenreekstype in Python 3.
Antwoord 2, autoriteit 18%
Ik weet dat dit een oud onderwerp is, maar omdat het de eerste is die op Google wordt getoond en aangezien ik geen van de antwoorden bevredigend vind, laat ik dit hier staan voor toekomstig gebruik:
sixis een Python 2 en 3 compatibiliteitsbibliotheek die dit probleem al behandelt. Je kunt dan zoiets als dit doen:
import six
if isinstance(value, six.string_types):
pass # It's a string !!
Als u de code inspecteert, vindt u dit:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
Antwoord 3, autoriteit 6%
In Python 3.x of Python 2.7.6
if type(x) == str:
Antwoord 4, autoriteit 2%
u kunt doen:
var = 1
if type(var) == int:
print('your variable is an integer')
of:
var2 = 'this is variable #2'
if type(var2) == str:
print('your variable is a string')
else:
print('your variable IS NOT a string')
hoop dat dit helpt!
Antwoord 5
De typemodule bestaat ook als je meer dan ints en strings aan het controleren bent.
http://docs.python.org/library/types.html
Antwoord 6
Bewerken op basis van een beter antwoord hieronder. Ga naar ongeveer 3 antwoorden en ontdek hoe cool basestring is.
Oud antwoord:
Pas op voor unicode-strings, die je op verschillende plaatsen kunt krijgen, inclusief alle COM-aanroepen in Windows.
if isinstance(target, str) or isinstance(target, unicode):
Antwoord 7
aangezien basestring
niet is gedefinieerd in Python3, kan deze kleine truc helpen om de code compatibel te maken:
try: # check whether python knows about 'basestring'
basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
basestring=str
daarna kunt u de volgende test uitvoeren op zowel Python2 als Python3
isinstance(myvar, basestring)
Antwoord 8
Python 2 / 3 inclusief unicode
from __future__ import unicode_literals
from builtins import str # pip install future
isinstance('asdf', str) # True
isinstance(u'asdf', str) # True
http://python-future.org/overview.html
Antwoord 9
Dus,
Je hebt tal van opties om te controleren of je variabele een string is of niet:
a = "my string"
type(a) == str # first
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth
Deze bestelling is bedoeld.
Antwoord 10
Veel goede suggesties van anderen hier, maar ik zie geen goede cross-platform samenvatting. Het volgende zou een goede introductie moeten zijn voor elk Python-programma:
def isstring(s):
# if we use Python 3
if (sys.version_info[0] >= 3):
return isinstance(s, str)
# we use Python 2
return isinstance(s, basestring)
In deze functie gebruiken we isinstance(object, classinfo)
om te zien of onze invoer een str
is in Python 3 of een basestring
in Python 2.
Antwoord 11
Ook wil ik opmerken dat als je wilt controleren of het type van een variabele een specifiek type is, je het type van de variabele kunt vergelijken met het type van een bekend object.
Voor string kun je dit gebruiken
type(s) == type('')
Antwoord 12
Alternatieve manier voor Python 2, zonder gebruik van basestring:
isinstance(s, (str, unicode))
Maar werkt nog steeds niet in Python 3 omdat unicode
niet is gedefinieerd (in Python 3).
Antwoord 13
a = '1000' # also tested for 'abc100', 'a100bc', '100abc'
isinstance(a, str) or isinstance(a, unicode)
retourneert True
type(a) in [str, unicode]
retourneert True
Antwoord 14
Hier is mijn antwoord om zowel Python 2 als Python 3 te ondersteunen, samen met deze vereisten:
- Geschreven in Py3-code met minimale Py2-compatcode.
- Verwijder Py2 compat-code later zonder onderbreking. D.w.z. streef alleen naar verwijdering, geen wijziging van Py3-code.
- Vermijd het gebruik van
six
of een vergelijkbare compat-module, omdat deze de neiging hebben om te verbergen wat
probeert te worden bereikt. - Toekomstbestendig voor een potentiële Py4.
import sys
PY2 = sys.version_info.major == 2
# Check if string (lenient for byte-strings on Py2):
isinstance('abc', basestring if PY2 else str)
# Check if strictly a string (unicode-string):
isinstance('abc', unicode if PY2 else str)
# Check if either string (unicode-string) or byte-string:
isinstance('abc', basestring if PY2 else (str, bytes))
# Check for byte-string (Py3 and Py2.7):
isinstance('abc', bytes)
Antwoord 15
Als je niet afhankelijk wilt zijn van externe bibliotheken, werkt dit zowel voor Python 2.7+ als Python 3 (http:// ideone.com/uB4Kdc):
# your code goes here
s = ["test"];
#s = "test";
isString = False;
if(isinstance(s, str)):
isString = True;
try:
if(isinstance(s, basestring)):
isString = True;
except NameError:
pass;
if(isString):
print("String");
else:
print("Not String");
Antwoord 16
U kunt eenvoudig de functie isinstancegebruiken om ervoor te zorgen dat de invoergegevens de indeling stringof unicodehebben. Onderstaande voorbeelden zullen u helpen om het gemakkelijk te begrijpen.
>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string', unicode)
True
Antwoord 17
s = '123'
issubclass(s.__class__, str)
Antwoord 18
Dit is hoe ik het doe:
if type(x) == type(str()):
Antwoord 19
Ik heb gezien:
hasattr(s, 'endswith')
Antwoord 20
>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True