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
延伸文章資訊
- 1Python String encode() - Programiz
Using the string encode() method, you can convert unicode strings into any encodings supported by...
- 2Unicode HOWTO — Python 3.10.7 documentation
Python's string type uses the Unicode Standard for representing ... This means that UTF-8 strings...
- 3Converting Between Unicode and Plain Strings - O'Reilly
Convert Unicode to plain Python string: "encode" unicodestring = u"Hello world" utf8string = unic...
- 4Python 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...
- 5A 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...