How to Convert a String to UTF-8 in Python? - Studytonight
文章推薦指數: 80 %
In this article, we will learn to convert a string to UTF-8 in Python. We will use some built-in functions and some custom code as well. MastertheGoProgrammingLanguage(Golang)andGetjob-ready.🥳 🚀 BestDevOpsRoadmapforBeginners(inHindi).😍🤩 TheUltimateDSARoadmapfor2022.😍🤩 Signup/SignIn DarkModeOn/Off InteractiveLearning LearnHTML LearnCSS LearnJavaScript CLanguage CTutorial CPrograms(100+) CCompiler ExecuteCprogramsonline. C++Language C++Tutorial StandardTemplateLibrary C++Programs(100+) C++Compiler ExecuteC++programsonline. Python PythonTutorial PythonProjects PythonPrograms PythonHowTos NumpyModule MatplotlibModule TkinterModule NetworkProgrammingwithPython LearnWebScraping MoreinPython... PythonCompiler ExecutePythoncodeonline. Java CoreJavaTutorial JavaPrograms(100+) JavaCodeExamples(100+) Servlet JSP-JavaServerPages JavaTypeConversionExamples JavaWrapperClass SpringFramework Java11 MoreinJava... JavaCompiler ExecuteJavacodeonline. ComputerSci.(GATE) OperatingSystem ComputerArchitecture ComputerNetwork Database DBMS LearnSQL MongoDB PL/SQL PracticeSQL ExecuteSQLQueriesonline. MoreTutorials... Android Kotlin GameDevelopment GOLanguage GITGuide LinuxGuide Docker SpringBoot PHP HTMLTags(AtoZ) CSS JavaScript SASS/SCSS Tests MCQstotestyourknowledge. Forum Engagewiththecommunity. Compilers Compilerstoexecutecodeinbrowser. LearntoCode Library Tests Forum TechBlog Login Index Explore: TutorialsLibrary MCQTests Curious? LearnCoding! PythonBasics FloatRoundtoTwoDecimalsCheckifaVariableExistsCheckPythonVersionYieldkeywordinUpgradePythonPackagesGenerateRandomValueAssertinPythonUnderscoreinPythonConvertByteToHexCommentinPythonErrorHandlinginPythonNormalvsKeywordArgumentsScopeofvariableinIfStatementPythonOOPS CreateClassCreateanObjectStaticvsClassMethodFindAllSubClassesPassMethodasArgumentPythonString PrintColourfulTextStringSlicingRemovenumbersfromStringStringtoCharArrayRemovetrailingnewlinesCreateMultiLineStringConvertStringtoStringArrayConvertStringtoByteConvertBytetoStringRemoveSpacefromStringCounttheStringOccurrenceConvertStringtoUTF-8ReplaceStringMD5SumOfStringDecodeHTMLEntitiesPythonList ConvertListtoStringConcatenateListsFindAverageofaListFindMaxFromListListSubtractionCountUniqueValuesinListCreatingArrayCheckListSameElementsListstoDictionaryDel,RemoveandPopPermutationofListMergeTwoListsLongestStringinListPrintRandomfromListHowtoSliceHowtoaddListasArgumentDeleteFromListTupletoListReadListElementsRotateaListTwoListAdditionPythonTuple PassTupleasanArgumentHowtoAddPythonDate&Time CompareTwoDatesAddDaystoDateCurrentdateandtimeGetYearfromDatePythonExecutionTimeConvertSecondstoMinutesDatetoStringConvertDateTimetoSecondsGetMonthNamePythonSet JointwoSetsAddElementsintoSetDeleteElementsfromSetAccessSetElementsSetwithrangeCreateanImmutableSetAddListtoSetPythonDictionary FindKeyFromValueinDictionaryReverseDictionaryCheckValueExistsinDictionaryListofValueFromDictionaryPythonFileandI/O UnzipFileReadXMLfileinpythonReadCSVfileinPythonReadJSONFileCheckFileSizeListallfilesReadYAMLinPythonReadCSVToListAppendTextToaFileCheckFileExistinPythonFindfileswithCertainExtensionGetLastofPathReadFileFromLine2SearchandReplaceFileTextReadFirstLineGetTheHomeDirectorySearchandReplaceTextinFileCheckIfFileisEmptyPythonJSON PrintPrettyJSONConvertJSONtoDictionary ←PrevNext→HomePythonHowTosHowtoConvertaStringtoUTF-8inPython?HowtoConvertaStringtoUTF-8inPython? Inthisarticle,wewilllearntoconvertastringtoUTF-8inPython.Wewillusesomebuilt-infunctionsandsomecustomcodeaswell.Let'sfirsthaveaquicklookoverwhatisastringinPython. PythonString TheStringisatypeinpythonlanguagejustlikeinteger,float,boolean,etc.Datasurroundedbysinglequotesordoublequotesaresaidtobeastring.Astringisalsoknownasasequenceofcharacters. string1="apple" string2="Preeti125" string3="12345" string4="pre@12" WhatisUTF-8inPython? UTFis“UnicodeTransformationFormat”,and‘8’means8-bitvaluesareusedintheencoding.Itisoneofthemostefficientandconvenientencodingformatsamongvariousencodings.InPython,Stringsarebydefaultinutf-8formatwhichmeanseachalphabetcorrespondstoauniquecodepoint.utf-8encodesaUnicodestringtobytes.Theuserreceivesstringdataontheserverinsteadofbytesbecausesomeframeworksorlibraryonthesystemhasimplicitlyconvertedsomerandombytestostringandithappensduetoencoding. Ausermightencounterasituationwherehisserverreceivesutf-8charactersbutwhenhetriestoretrieveitfromthequerystring,hegetsASCIIcoding.Therefore,inordertoconverttheplainstringtoutf-8,wewillusetheencode()methodtoconvertastringtoutf-8inpython3. Useencode()toconvertaStringtoUTF-8 Theencode()methodreturnstheencodedversionofthestring.Incaseoffailure,aUnicodeDecodeErrorexceptionmayoccur. Syntax string.encode(encoding='UTF-8',errors='strict') Parameters encoding-theencodingtypelike'UTF-8',ASCII,etc. errors-responsewhenencodingfails. Therearesixtypesoferrorresponses: strict-defaultresponsewhichraisesaUnicodeDecodeErrorexceptiononfailure ignore-ignorestheunencodableUnicodefromtheresult replace-replacestheunencodableUnicodetoaquestionmark? xmlcharrefreplace-insertsXMLcharacterreferenceinsteadofunencodableUnicode backslashreplace-insertsa\uNNNNescapesequenceinsteadofunencodableUnicode namereplace-insertsa\N{...}escapesequenceinsteadofunencodableUnicode Bydefault,theencode()methoddoesnottakeanyparameters. Example #unicodestring string='pythön!' #defaultencodingtoutf-8 string_utf=string.encode() print('Theencodedversionis:',string_utf) Theencodedversionis:b'pyth\xc3\xb6n!' Conclusion Inthisarticle,welearnedtoconvertaplainstringtoutf-8formatusingencode()method.Youcanalsotryusingdifferentencodingformatsanderrorparameters. ←CounttheStringOccurrence←PREVReplaceString→NEXT→ MCQTests PrepareforyournexttechnicalInterview.Weaddnewtestseveryweek. Explore
延伸文章資訊
- 1Convert 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...
- 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...
- 3How to Convert a String to UTF-8 in Python? - Studytonight
In this article, we will learn to convert a string to UTF-8 in Python. We will use some built-in ...
- 4Unicode HOWTO — Python 3.10.7 documentation
Python's string type uses the Unicode Standard for representing ... This means that UTF-8 strings...
- 5Python String encode() - Programiz
Using the string encode() method, you can convert unicode strings into any encodings supported by...