How to check if type of a variable is string?
Is there a way to check if the type of a variable in python is a
for integer values?
In Python 2.x, you would do
basestring is the abstract superclass of
unicode. It can be used to test whether an object is an instance of
In Python 3.x, the correct test is
bytes class isn't considered a string type in Python 3.
Read more... Read less...
I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:
six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:
import six if isinstance(value, six.string_types): pass # It's a string !!
Inspecting the code, this is what you find:
import sys PY3 = sys.version_info == 3 if PY3: string_types = str, else: string_types = basestring,
In Python 3.x or Python 2.7.6
if type(x) == str:
you can do:
var = 1 if type(var) == int: print('your variable is an integer')
var2 = 'this is variable #2' if type(var2) == str: print('your variable is a string') else: print('your variable IS NOT a string')
hope this helps!
Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.
Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.
if isinstance(target, str) or isinstance(target, unicode):