Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable is string with python 2 and 3 compatibility

I'm aware that I can use: isinstance(x, str) in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str) work as expected in python-2.x? Or will I need to check the version and use isinstance(x, basestr)?

Specifically, in python-2.x:

>>>isinstance(u"test", str) False 

and python-3.x does not have u"foo"

like image 803
Randall Hunt Avatar asked Jul 02 '12 21:07

Randall Hunt


People also ask

Are Python 2 and 3 compatible with each other?

The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.

How do you check if a variable is a specific string in Python?

To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.

How do you check if a string is equal to another string in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.


2 Answers

If you're writing 2.x-and-3.x-compatible code, you'll probably want to use six:

from six import string_types isinstance(s, string_types) 
like image 106
ecatmur Avatar answered Sep 20 '22 06:09

ecatmur


The most terse approach I've found without relying on packages like six, is:

try:   basestring except NameError:   basestring = str 

then, assuming you've been checking for strings in Python 2 in the most generic manner,

isinstance(s, basestring) 

will now also work for Python 3+.

like image 20
hbristow Avatar answered Sep 20 '22 06:09

hbristow