How can I check if a Python object is a string (either regular or Unicode)?
Use isinstance(obj, basestring)
for an object-to-test obj
.
Docs.
In order to check if your variable is something you could go like:
s='Hello World'
if isinstance(s,str):
#do something here,
The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type 'str' so you can use it in the isistance function.
If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and its string_types
attribute:
import six
if isinstance(obj, six.string_types):
print('obj is a string!')
Within six
(a very light-weight single-file module), it's simply doing this:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:
def is_string(obj):
try:
obj + ''
return True
except TypeError:
return False
wisefish was close with the duck-typing before he switched to the isinstance
approach, except that +=
has a different meaning for lists than +
does.
if type(varA) == str or type(varB) == str:
print 'string involved'
from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
You can test it by concatenating with an empty string:
def is_string(s):
try:
s += ''
except:
return False
return True
Edit:
Correcting my answer after comments pointing out that this fails with lists
def is_string(s):
return isinstance(s, basestring)