Created
July 26, 2019 15:27
-
-
Save darrenpmeyer/1a4620441ea5a8749793a91397927135 to your computer and use it in GitHub Desktop.
Python2 and Python3 compatible "is this a unicode string" check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
# the string to check is in 'candidate' | |
if isinstance(candidate, type(u"")): | |
print("This is a unicode string") | |
else: | |
# if it's a Py2 'str' or a Py3 'bytes' object, this will convert | |
# otherwise it'll raise an exception | |
candidate = candidate.decode('utf8') | |
""" | |
In Python2, you could check ``if type(candidate) == unicode``, but that doesn't work in Py3 because | |
all ``str`` are unicode and there's no ``unicode`` type | |
So... both have ``isinstance``, so we simply compare the type to the type of an example unicode string | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment