Use isinstance to check Unicode string

How can I do something like:

>>> s = u'hello' >>> isinstance(s,str) False 

But I would like isinstance return True for this Unicode encoded string. Is there a Unicode string object type?

+6
source share
3 answers

Python2: You can use basestring to test both :

 isinstance(unicode_or_bytestring, basestring) 

basestring is only available in Python 2 and is the abstract base type of str and unicode .

If you want to test only unicode , do it explicitly:

 isinstance(unicode_tring, unicode) 
+9
source

Is there a Unicode string object type?

Yes, it is called unicode :

 >>> s = u'hello' >>> isinstance(s, unicode) True >>> 

Note that in Python 3.x this type was removed because all lines are now Unicode .

+4
source

Is there a Unicode string object type?

Yes it works:

 >>> s = u'hello' >>> isinstance(s, unicode) True >>> 

This, however, is only useful if you know that it is unicode. Another solution is to use the six package, which will save you from python2.x and python3.x conversions and catches of unicode and str

 >>> unicode_s = u'hello' >>> s = 'hello' >>> isinstance(unicode_s, str) False >>> isinstance(unicode_s, unicode) True >>> isinstance(s, str) True >>> isinstance(unicode_s, str) False >>> isinstance(s, six.string_types) True >>> isinstance(unicode_s, six.string_types) True 
0
source

Source: https://habr.com/ru/post/971603/


All Articles