Python Check Variable Is String

Jun 6, 2019

Python 2.x

if isinstance(value, basestring):    pass

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

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.

six

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 sixif isinstance(value, six.string_types):    pass

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.