The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.
Since Python 3.0, the language's str type contains Unicode characters, meaning any string created using "unicode rocks!" , 'unicode rocks!'
There is a bytes type that holds raw bytes. This does not distinguish "Unicode or ASCII"; it only distinguishes Python types. A Unicode string may consist of purely characters in the ASCII range, and a bytestring may contain ASCII, encoded Unicode, or even non-textual data.
You have two options to create Unicode string in Python. Either use decode() , or create a new Unicode string with UTF-8 encoding by unicode(). The unicode() method is unicode(string[, encoding, errors]) , its arguments should be 8-bit strings.
Python 3 renamed the unicode
type to str
, the old str
type has been replaced by bytes
.
if isinstance(unicode_or_str, str):
text = unicode_or_str
decoded = False
else:
text = unicode_or_str.decode(encoding)
decoded = True
You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online.
Last but not least, you could just try to use the 2to3
tool to see how that translates the code for you.
If you need to have the script keep working on python2 and 3 as I did, this might help someone
import sys
if sys.version_info[0] >= 3:
unicode = str
and can then just do for example
foo = unicode.lower(foo)
You can use the six library to support both Python 2 and 3:
import six
if isinstance(value, six.string_types):
handle_string(value)
One can replace unicode
with u''.__class__
to handle the missing unicode
class in Python 3. For both Python 2 and 3, you can use the construct
isinstance(unicode_or_str, u''.__class__)
or
type(unicode_or_str) == type(u'')
Depending on your further processing, consider the different outcome:
Python 3
>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True
Python 2
>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With