How to check if type of a variable is string?

PythonStringVariablesTypes

Python Problem Overview


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

isinstance(x,int);

for integer values?

Python Solutions


Solution 1 - Python

In Python 2.x, you would do

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.


In Python 3.x, the correct test is

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.

Solution 2 - Python

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,
	

Solution 3 - Python

In Python 3.x or Python 2.7.6

if type(x) == str:

Solution 4 - Python

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!

Solution 5 - Python

Use type() or isinstance()

I don't know why not a single answer before me contains this simple type(my_variable) is str syntax, but using type() like this seems the most-logical and simple to me, by far:

(tested in Python3):

# Option 1: check to see if `my_variable` is of type `str`
type(my_variable) is str

# Option 2: check to see if `my_variable` is of type `str`, including
# being a subclass of type `str` (ie: also see if `my_variable` is any object 
# which inherits from `str` as a parent class)
isinstance(my_variable, str)

The Python type() built-in function documentation is here: https://docs.python.org/3/library/functions.html#type. It states, in part, the following. Notice the note about isinstance():

> class type(object)
> class type(name, bases, dict, **kwds) > > With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__. > > The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

So, if you're checking the type of a class object instead of a simple variable, and you need to take subclasses into account, then use isinstance() instead. See its documentation here: https://docs.python.org/3/library/functions.html#isinstance.

Example code:

my_str = "hello"
my_int = 7

print(type(my_str) is str)
print(type(my_int) is str)

print()
print(isinstance(my_str, str))
print(isinstance(my_int, str))

Output:

> True > False > > True > False

Solution 6 - Python

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

Solution 7 - Python

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):

Solution 8 - Python

since basestring isn't defined in Python3, this little trick might help to make the code compatible:

try: # check whether python knows about 'basestring'
   basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
   basestring=str

after that you can run the following test on both Python2 and Python3

isinstance(myvar, basestring)

Solution 9 - Python

Python 2 / 3 including 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

Solution 10 - Python

Lots of good suggestions provided by others here, but I don't see a good cross-platform summary. The following should be a good drop in for any Python program:

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 this function, we use isinstance(object, classinfo) to see if our input is a str in Python 3 or a basestring in Python 2.

Solution 11 - Python

So,

You have plenty of options to check whether your variable is string or not:

a = "my string"
type(a) == str # first 
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth

This order is for purpose.

Solution 12 - Python

Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.

For string you can use this

type(s) == type('')

Solution 13 - Python

Alternative way for Python 2, without using basestring:

isinstance(s, (str, unicode))

But still won't work in Python 3 since unicode isn't defined (in Python 3).

Solution 14 - Python

Here is my answer to support both Python 2 and Python 3 along with these requirements:

  • Written in Py3 code with minimal Py2 compat code.
  • Remove Py2 compat code later without disruption. I.e. aim for deletion only, no modification to Py3 code.
  • Avoid using six or similar compat module as they tend to hide away what is trying to be achieved.
  • Future-proof for a potential 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)

Solution 15 - Python

a = '1000' # also tested for 'abc100', 'a100bc', '100abc'

isinstance(a, str) or isinstance(a, unicode)

returns True

type(a) in [str, unicode]

returns True

Solution 16 - Python

If you do not want to depend on external libs, this works both for Python 2.7+ and 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");

Solution 17 - Python

You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.

>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

Solution 18 - Python

Summarizing:

There doesn't seem to be a portable way to do it if you want both Python2 and Python3, and want to include unicode as well. I wound up using this idiom:

# Near the top of my program
if sys.version_info[0] >= 3:
    basestring = str

Then any time I want to test an object to see if it's a string:

if isinstance(obj, basestring):
    ...

Frankly, I'm a little shocked that Python3 dropped basestring as well as types.StringTypes. I see no reason to drop them, and keeping either of them would have made this problem solveable.

Solution 19 - Python

s = '123'
issubclass(s.__class__, str)

Solution 20 - Python

This is how I do it:

if type(x) == type(str()):

Solution 21 - Python

I've seen:

hasattr(s, 'endswith') 

Solution 22 - Python

>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionc_pleaseUpvoteView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonAndré FratelliView Answer on Stackoverflow
Solution 3 - PythonTexom512View Answer on Stackoverflow
Solution 4 - PythonF. TaylorView Answer on Stackoverflow
Solution 5 - PythonGabriel StaplesView Answer on Stackoverflow
Solution 6 - PythondicatoView Answer on Stackoverflow
Solution 7 - PythonWade HatlerView Answer on Stackoverflow
Solution 8 - PythonumläuteView Answer on Stackoverflow
Solution 9 - PythoncrizCraigView Answer on Stackoverflow
Solution 10 - PythonduanevView Answer on Stackoverflow
Solution 11 - PythonPatNowakView Answer on Stackoverflow
Solution 12 - PythonDaniil GrankinView Answer on Stackoverflow
Solution 13 - PythonyprezView Answer on Stackoverflow
Solution 14 - PythonCasView Answer on Stackoverflow
Solution 15 - Pythonbe_good_do_goodView Answer on Stackoverflow
Solution 16 - PythonmPrinCView Answer on Stackoverflow
Solution 17 - PythonHassan MehmoodView Answer on Stackoverflow
Solution 18 - PythonEdward FalkView Answer on Stackoverflow
Solution 19 - Pythonvadim vaduxaView Answer on Stackoverflow
Solution 20 - PythonUserView Answer on Stackoverflow
Solution 21 - Pythonfast toothView Answer on Stackoverflow
Solution 22 - PythonRichard UrbanView Answer on Stackoverflow