How can I do something like:
JavaScript
x
4
1
>>> s = u'hello'
2
>>> isinstance(s,str)
3
False
4
But I would like isinstance
to return True
for this Unicode encoded string. Is there a Unicode string object type?
Advertisement
Answer
Test for str
:
JavaScript
1
2
1
isinstance(unicode_or_bytestring, str)
2
or, if you must handle bytestrings, test for bytes
separately:
JavaScript
1
2
1
isinstance(unicode_or_bytestring, bytes)
2
The two types are deliberately not exchangible; use explicit encoding (for str
-> bytes
) and decoding (bytes
-> str
) to convert between the types.
In Python 2, where the modern Python 3 str
type is called unicode
and str
is the precursor of the Python 3 bytes
type, you could use basestring
to test for both:
JavaScript
1
2
1
isinstance(unicode_or_bytestring, basestring)
2
basestring
is only available in Python 2, and is the abstract base type of both str
and unicode
.
If you wanted to test for just unicode
, then do so explicitly:
JavaScript
1
2
1
isinstance(unicode_tring, unicode)
2