Python String encode() - Programiz

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

Using the string encode() method, you can convert unicode strings into any encodings supported by Python. By default, Python uses utf-8 encoding. Previous ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples PythonStringMethods PythonStringcapitalize() PythonStringcenter() PythonStringcasefold() PythonStringcount() PythonStringendswith() PythonStringexpandtabs() PythonStringencode() PythonStringfind() PythonStringformat() PythonStringindex() PythonStringisalnum() PythonStringisalpha() PythonStringisdecimal() PythonStringisdigit() PythonStringisidentifier() PythonStringislower() PythonStringisnumeric() PythonStringisprintable() PythonStringisspace() PythonStringistitle() PythonStringisupper() PythonStringjoin() PythonStringljust() PythonStringrjust() PythonStringlower() PythonStringupper() PythonStringswapcase() PythonStringlstrip() PythonStringrstrip() PythonStringstrip() PythonStringpartition() PythonStringmaketrans() PythonStringrpartition() PythonStringtranslate() PythonStringreplace() PythonStringrfind() PythonStringrindex() PythonStringsplit() PythonStringrsplit() PythonStringsplitlines() PythonStringstartswith() PythonStringtitle() PythonStringzfill() PythonStringformat_map() RelatedTopics Pythonstr() Pythonbytes() Pythonbytearray() Pythonopen() PythonStrings PythonErrorsandBuilt-inExceptions PythonStringencode() Inthistutorial,wewilllearnaboutthePythonStringencode()methodwiththehelpofexamples. Theencode()methodreturnsanencodedversionofthegivenstring. Example title='PythonProgramming' #changeencodingtoutf-8 print(title.encode()) #Output:b'PythonProgramming' SyntaxofStringencode() Thesyntaxofencode()methodis: string.encode(encoding='UTF-8',errors='strict') Stringencode()Parameters Bydefault,theencode()methoddoesn'trequireanyparameters. Itreturnsanutf-8encodedversionofthestring.Incaseoffailure,itraisesaUnicodeDecodeErrorexception. However,ittakestwoparameters: encoding-theencodingtypeastringhastobeencodedto errors-responsewhenencodingfails.Therearesixtypesoferrorresponse strict-defaultresponsewhichraisesaUnicodeDecodeErrorexceptiononfailure ignore-ignorestheunencodableunicodefromtheresult replace-replacestheunencodableunicodetoaquestionmark? xmlcharrefreplace-insertsXMLcharacterreferenceinsteadofunencodableunicode backslashreplace-insertsa\uNNNNescapesequenceinsteadofunencodableunicode namereplace-insertsa\N{...}escapesequenceinsteadofunencodableunicode Example1:EncodetoDefaultUtf-8Encoding #unicodestring string='pythön!' #printstring print('Thestringis:',string) #defaultencodingtoutf-8 string_utf=string.encode() #printresult print('Theencodedversionis:',string_utf) Output Thestringis:pythön! Theencodedversionis:b'pyth\xc3\xb6n!' Example2:Encodingwitherrorparameter #unicodestring string='pythön!' #printstring print('Thestringis:',string) #ignoreerror print('Theencodedversion(withignore)is:',string.encode("ascii","ignore")) #replaceerror print('Theencodedversion(withreplace)is:',string.encode("ascii","replace")) Output Thestringis:pythön! Theencodedversion(withignore)is:b'pythn!' Theencodedversion(withreplace)is:b'pyth?n!' Note:Trydifferentencodinganderrorparametersaswell. StringEncoding SincePython3.0,stringsarestoredasUnicode,i.e.eachcharacterinthestringisrepresentedbyacodepoint.So,eachstringisjustasequenceofUnicodecodepoints. Forefficientstorageofthesestrings,thesequenceofcodepointsisconvertedintoasetofbytes.Theprocessisknownasencoding. Therearevariousencodingspresentwhichtreatastringdifferently.Thepopularencodingsbeingutf-8,ascii,etc. Usingthestringencode()method,youcanconvertunicodestringsintoanyencodingssupportedbyPython.Bydefault,Pythonusesutf-8encoding. PreviousTutorial: PythonStringexpandtabs() NextTutorial: PythonStringfind() Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank PythonReferencesPythonLibraryPythonStringreplace()PythonLibraryPythonStringmaketrans()PythonLibraryPythonStringtitle()PythonLibraryPythonStringisdecimal() TryPROforFREE LearnPythonInteractively



請為這篇文章評分?