Python Check Variable Is String

June 6, 2019

Python 2.x

if isinstance(value, basestring):

NOTE: basestring

This abstract type is the superclass for str and unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode))

Python 3.x

if isinstance(value, str):

NOTE: str

NOTE: Python 2 vs Python 3: Byte, Str and Unicode: In Python 3.x there are bytes and bytearray which are not string.


There is a convenient six library which support Python 2 and Python 3.

Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification. six consists of only one Python file, so it is painless to copy into a project.

import six

if isinstance(value, six.string_types):
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.