Advertisement
Advertisement


How to check if type of a variable is string?


Question

Is there a way to check if the type of a variable in python is a string, like:

isinstance(x,int);

for integer values?

2020/04/19
1
799
4/19/2020 5:47:44 PM


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[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,
2017/08/31

In Python 3.x or Python 2.7.6

if type(x) == str:
2015/08/19

you can do:

var = 1
if type(var) == int:
   print('your variable is an integer')

or:

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!

2017/10/25

The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html

2011/01/31

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):
2014/12/01

Source: https://stackoverflow.com/questions/4843173
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]