Python String encode() - Programiz
文章推薦指數: 80 %
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
延伸文章資訊
- 1Unicode HOWTO — Python 3.10.7 documentation
Python's string type uses the Unicode Standard for representing ... This means that UTF-8 strings...
- 2Converting Between Unicode and Plain Strings - O'Reilly
Convert Unicode to plain Python string: "encode" unicodestring = u"Hello world" utf8string = unic...
- 3Understand the encoding/decoding of Python strings (Unicode ...
UTF-8 is an abbreviation for Unicode Transformation Format — 8 bits. The “8” here means 8-bit blo...
- 4Day27 Python 基礎- 字符轉編碼操作 - iT 邦幫忙
UTF-8 是一種針對Unicode的可變長度字元編碼,英文字符一樣會依照ASCII碼規範,只占一個字節8bit,而中文字符的話,統一就占三個字節. 回顧可以參考字符編碼.
- 5Convert UTF-8 to string literals in Python - Stack Overflow
The u'' syntax only works for string literals, e.g. defining values in source code. Using the syn...