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
延伸文章資訊
- 1Python Convert Unicode to Bytes, ASCII, UTF-8, Raw String
Converting Unicode strings to bytes is quite common these days because it is necessary to convert...
- 2Understand 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...
- 3Unicode HOWTO — Python 3.10.7 documentation
Python's string type uses the Unicode Standard for representing ... This means that UTF-8 strings...
- 4A Guide to Unicode, UTF-8 and Strings in Python
Sure! Let's see all we have covered so far visually. By default in Python 3, we are on the left s...
- 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...