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"
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.
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.
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.
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)
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+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With