Python String Decode Method - Linux Hint
文章推薦指數: 80 %
Python used to store the string in Unicode form. Encoding would convert a simple string to a group of bytes while decoding will convert group of bytes to a ... ThePythonlanguageisusedtostorethestringintheformofUnicode.WithinUnicode,asimplecodepointisutilizedtorepresentasinglecharacterofaUnicode.Wehavetoknowtwoterms:encodeanddecode.Theencodingwouldconvertasimplestringtoagroupofbyteswhiledecodingwillconvertthegroupofbytestoarealstringonceagain. So,withinthisarticletoday,wewillbedecodingastringtoanoriginalonewiththeencode()anddecode()function.Besuretoconfigurethepython3packageonyourLinuxsystem.Let’sstarttoday’sarticlebylaunchingtheterminalconsoleusingtheCtrl+Alt+T. Example1 Wewillbestartingthefirstexamplewithinthepython3consoleoftheUbuntu20.04shellterminal.So,wehavestarteditwiththekeywordPython3asshownintheoutputbeneath. $python3 Theconsoleisnowreadytobeused.So,wehaveinitializedastringvariablenamed“s”andassigneditsomevalue.Itsvaluecontainsamixofintegersthatarebeingconvertedintoacharactertypeandconcatenatedwithastringtypevalue“hello”.Onthenextline,wehaveinitializedanothervariablenamed“enc”. Theencode()methodhasbeenusedheretoencodetheoriginalvariable“s”toutf-8encodingandsavedtheencodedstringtoavariable“enc”.Thenextconsecutivelineisusingaprintclausetoprinttheencodedstringvaluei.e.“enc”.Theterminalshowstheencodedstringinbytes.Thescriptthatisexplainedaboveiscitedhere. >>>s=chr(13)+‘hello’+chr(14) >>>enc=s.encode(‘utf-8’) >>>print(enc) b’\rhello\x0e’ It’stimetodecodebacktheencodedstringtoitsoriginalform.So,wehaveappliedthedecodefunctiononthevariable“enc”toconvertitbacktotheoriginalstringandsaveittothevariable“dec”.Theprintstatementhasbeenexecutedtoprintthedecodedstringontheshellasshownintheimagebelowi.e.,hello.Thescriptthatisexplainedaboveiscitedhere. >>>=enc.decode() >>>print(dec) hello Example2 Let’stakeanotherexampletodecodeastring.WehavecreatedanewPythontypefile.AfteraddingthePythonsupport,wehaveinitializedastring“str”andencodedittoutf-8typebyteformatusingtheencodefunction.Theerrorsaresetto“strict”toraiseonlyaUnicodeErrorandtherestwillbeignored. Theencodedstringwillbesavedtothevariable“enc”andtheprintclausewillprintthetypeofencodedvariableusingthe“type()”method.Theprintstatementwillprintouttheencodedstringandthedecodefunctionwilldecodeitbacktotheoriginalone.Thedecodedstringwillbeprintedout. Thescriptthatisexplainedaboveiscitedhere. #!/usr/bin/python3 str=“HelloLinux” enc=str.encode(‘utf-8’,‘strict’) print(type(enc)) print(“Theencodedstring:”,enc) dec=enc.decode(‘utf-8’,‘strict’) print(“Thedecodedstring:”,dec) ExecutionofthisPythonfiledisplaysthetypeofencodedstringi.e.,bytesandshowstheencodedanddecodedstringseparately. $python3decode.py Example3 Let’sendthisarticlewiththelastexample.Thistimewewillbeconvertingourstringtoutf_16formatofbytes.So,wehaveinitializedastringandencodedittoutf_16encodingusingtheencode()functiononit. Theencodedstringhasbeensavedtovariable“enc”andwehaveprinteditstypeandvalue.Theencodedstringvariablehasbeendecodedintoanoriginalonewiththeuseofthedecode()functiononthe“enc”variableandprintedoutontheshell..Thescriptthatisexplainedaboveiscitedhere. #!/usr/bin/python3 str=“HelloLinux” enc=str.encode(“utf-16”) print(type(enc)) print(“Theencodedstring:”,enc) dec=enc.decode(‘utf-16’,‘strict’) print(“Thedecodedstring:”,dec) AfterrunningthisupdatedcodeofPythonwiththepython3keyword,wehavegotthedisplayofencodedstringtypeas“bytes”alongwiththeencodedanddecodedstring. $python3decode.py Conclusion Withinthisarticle,wehavedemonstratedsimpleexamplestodecodeanencodedstringbacktotheoriginalone.Wehaveencodedthesimplestringstoutf-8andutf-16bytesformatsandthendecodethembacktotheoriginalstring.Wehopeitwillbehelpful. Abouttheauthor KalsoomBibi Hello,IamafreelancewriterandusuallywriteforLinuxandothertechnologyrelatedcontent Viewallposts RELATEDLINUXHINTPOSTS PyTorchTutorialKerasTutorialt-SNESklearnKNNinSklearnCrossValidationinSklearnPandasUnionPandasrolling().apply()Function
延伸文章資訊
- 1Python String encode() decode() - DigitalOcean
Python string encode() function is used to encode the string using the provided encoding. This fu...
- 2Unicode HOWTO — Python 3.10.7 documentation
decode() is str.encode() , which returns a bytes representation of the Unicode string, encoded in...
- 3Python String Decode Method - Linux Hint
Python used to store the string in Unicode form. Encoding would convert a simple string to a grou...
- 4Decode UTF-8 in Python | Delft Stack
- 5Python Strings decode() method - GeeksforGeeks