Skip to content

Instantly share code, notes, and snippets.

@darrenpmeyer
Created July 26, 2019 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenpmeyer/1a4620441ea5a8749793a91397927135 to your computer and use it in GitHub Desktop.
Save darrenpmeyer/1a4620441ea5a8749793a91397927135 to your computer and use it in GitHub Desktop.
Python2 and Python3 compatible "is this a unicode string" check
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