NameError: name 'unicode' is not defined in Python | bobbyhadz

文章推薦指數: 80 %
投票人數:10人

The Python "NameError name 'unicode' is not defined" occurs when using the unicode object in Python 3. To solve the error, replace all calls ... ☰HomeBookAboutContactsHomeBookAboutContactsGitHubLinkedinTwitterNameError:name'unicode'isnotdefinedinPythonBorislavHadzhievLastupdated:Apr20,2022PhotofromUnsplashNameError:name'unicode'isnotdefinedinPython#ThePython"NameErrorname'unicode'isnotdefined"occurswhenusingthe unicodeobjectinPython3.Tosolvetheerror,replaceallcallsto unicode()withstr()becauseunicodewasrenamedtostrinPython3.main.pyCopied!result=str('ABC') print(result)#👉️'ABC' Makesuretoreplacealloccurrencesofunicodewithstrinyourcode.Alternatively,youcandeclareaunicodevariableandsetitsvaluetothe strclass.main.pyCopied!importsys ifsys.version_info[0]>=3: unicode=str print(unicode('ABC'))#👉️"ABC" OurifstatementchecksiftheversionofthePythoninterpreterisgreateror equalto3,andifitis,wesettheunicodevariabletothestrclass.EversincePython3,thelanguageusestheconceptsoftextandbinarydatainsteadofunicodestringsand8-bitstrings.AlltextinPythonisunicode,howeverencodedUnicodeisrepresentedasbinary data.Youcanusethestrtypetostoretextandthebytestypetostorebinary data.main.pyCopied!my_text='hello' my_binary_data=bytes(my_text,'utf-8') print(my_binary_data)#👉️b'hello' InPython3youcannolongeruseu'...'literalsforUnicodetextbecauseall stringsarenowunicode.However,youmustuseb'...'literalsforbinarydata.Youcanusestr.encode()togofromstrtobytesandbytes.decode()to gofrombytestostr.main.pyCopied!my_text='hello' my_binary_data=my_text.encode('utf-8') print(my_binary_data)#👉️b'hello' my_text_again=my_binary_data.decode('utf-8') print(my_text_again)#👉️'hello' Thestr.encode()methodistheoppositeofbytes.decode()andreturnsa bytesrepresentationoftheunicodestring,encodedintherequestedencoding.Youcanalsousebytes(s,encoding=...)andstr(b,encoding=...).main.pyCopied!my_text='hello' my_binary_data=bytes(my_text,encoding='utf-8') print(my_binary_data)#👉️b'hello' my_text_again=str(my_binary_data,encoding='utf-8') print(my_text_again)#👉️'hello' Thestrclassreturnsa stringversionofthegivenobject.Ifanobjectisnotprovided,theclass returnsanemptystring.Thesyntaxforusingthe bytesclassisthe same,exceptthatabprefixisadded.Conclusion#ThePython"NameErrorname'unicode'isnotdefined"occurswhenusingthe unicodeobjectinPython3.Tosolvetheerror,replaceallcallsto unicode()withstr()becauseunicodewasrenamedtostrinPython3.IwroteabookinwhichIshareeverythingIknowabouthowtobecomeabetter,moreefficientprogrammer.YoucanusethesearchfieldonmyHomePagetofilterthroughallofmyarticles.ShareShareShareShareShareBorislavHadzhievWebDeveloperTwitterGitHubLinkedinSUPPORTME:)AboutContactsPolicyTerms&ConditionsTwitterGitHubLinkedinCopyright©2022BorislavHadzhievSearchforposts0..................................................................................................................................................................



請為這篇文章評分?