Python String encode() decode() - DigitalOcean

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

This function returns the bytes object. If we don't provide encoding, “utf-8” encoding is used as default. Python Bytes decode(). Python bytes ... Getalertedwhenassetsaredown,slow,orvulnerabletoSSLattacks—allfreeforamonth.Learnmore->We'rehiringBlogDocsGetSupportSalesProductsFeaturedProductsDropletsScalablevirtualmachinesKubernetesManagedKubernetesclustersAppPlatformGetappstomarketfasterFunctionsServerlesscomputesolutionDatabasesWorry-freesetup&maintenanceComputeDropletsKubernetesAppPlatformFunctionsStorageSpacesObjectStorageVolumesBlockStorageNetworkingVirtualPrivateCloud(VPC)CloudFirewallsLoadBalancersReservedIPsDNSManagedDatabasesMongoDBMySQLPostgreSQLRedis™ToolsandServicesAPICLISupportPlansTerraformProviderContainerManagementToolsMonitoringUptimeTeamsSeeallproductsSolutionsTryDigitalOceanforfreeClickheretosignupandget$200ofcredittotryourproductsover60days!SignupOurbusinesssolutionsWebsiteHostingVPSHostingByusecaseCloudVPNWeb&MobileAppsGameDevelopmentVideoStreamingSaaSPlatformsBlockchainQuestions?SpeakWithAnExpertTodaySeeallsolutionsMarketplaceCommunityOurcommunityCommunityHomeDevOpsanddevelopmentguidesCSS-TricksAllthingswebdesignResourcesTutorialsQuestionsAndAnswersToolsWriteforDOnationsCustomerStoriesDigitalOceanBlogGetInvolvedHatchStartupProgramOpenSourceSponsorshipsHacktoberfestDeployDOImpactDocumentationQuickStartDropletsStorageAppPlatformAPIReferenceDomainsandDNSPricingLoginSigninCommunityDigitalOceanSignupSignupCommunityDigitalOceanWe'rehiringBlogDocsGetSupportSalesTutorialsQuestionsTechTalksLearningPathsProductDocsSocialImpactSearchCommunityCONTENTSPythonStringencode()PythonBytesdecode()RelatedPythontimesleep()ViewVectorsinPython-AQuickIntroduction!View//Tutorial//PythonStringencode()decode()PublishedonAugust3,2022PythonPythonStringByPankajDeveloperandauthoratDigitalOcean.Whilewebelievethatthiscontentbenefitsourcommunity,wehavenotyetthoroughlyreviewedit.Ifyouhaveanysuggestionsforimprovements,pleaseletusknowbyclickingthe“reportanissue“buttonatthebottomofthetutorial.PythonStringencode() Pythonstringencode()functionisusedtoencodethestringusingtheprovidedencoding.Thisfunctionreturnsthebytesobject.Ifwedon’tprovideencoding,“utf-8”encodingisusedasdefault. PythonBytesdecode() Pythonbytesdecode()functionisusedtoconvertbytestostringobject.Boththesefunctionsallowustospecifytheerrorhandlingschemetouseforencoding/decodingerrors.Thedefaultis‘strict’meaningthatencodingerrorsraiseaUnicodeEncodeError.Someotherpossiblevaluesare‘ignore’,‘replace’and‘xmlcharrefreplace’.Let’slookatasimpleexampleofpythonstringencode()decode()functions. str_original='Hello' bytes_encoded=str_original.encode(encoding='utf-8') print(type(bytes_encoded)) str_decoded=bytes_encoded.decode() print(type(str_decoded)) print('Encodedbytes=',bytes_encoded) print('DecodedString=',str_decoded) print('str_originalequalsstr_decoded=',str_original==str_decoded) Output: Encodedbytes=b'Hello' DecodedString=Hello str_originalequalsstr_decoded=True Aboveexampledoesn’tclearlydemonstratetheuseofencoding.Let’slookatanotherexamplewherewewillgetinputsfromtheuserandthenencodeit.Wewillhavesomespecialcharactersintheinputstringenteredbytheuser. str_original=input('Pleaseenterstringdata:\n') bytes_encoded=str_original.encode() str_decoded=bytes_encoded.decode() print('Encodedbytes=',bytes_encoded) print('DecodedString=',str_decoded) print('str_originalequalsstr_decoded=',str_original==str_decoded) Output: Pleaseenterstringdata: aåb∫cçd∂e´´´ƒg©1¡ Encodedbytes=b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1' DecodedString=aåb∫cçd∂e´´´ƒg©1¡ str_originalequalsstr_decoded=True YoucancheckoutcompletepythonscriptandmorePythonexamplesfromourGitHubRepository. Reference:str.encode()APIDoc,bytes.decode()APIDoc Wanttolearnmore?JointheDigitalOceanCommunity!JoinourDigitalOceancommunityofoveramilliondevelopersforfree!GethelpandshareknowledgeinourQuestions&Answerssection,findtutorialsandtoolsthatwillhelpyougrowasadeveloperandscaleyourprojectorbusiness,andsubscribetotopicsofinterest.SignupAbouttheauthorsPankajauthorDeveloperandauthoratDigitalOcean.Stilllookingforananswer?AskaquestionSearchformorehelpWasthishelpful?YesNoCommentsJournalDev•October15,2020importrandomimportstringdefencode_text(s):new=‘’random.seed(2)letters=list(string.ascii_lowercase)newLtters=list(string.ascii_lowercase)random.shuffle(newletters)foriinrange(len(s)):print(s[i],letters.index(s[i]),newletters.index(s[i]))new+=letters[newletters(s[i])]returnnewdefdecode_text(s):#addcodetodecryptnew=‘’retuennewdefmain()text=‘yipscekbwektipn’print(“Originalstring:“,decode_text(text))if__name__==”__main__”:main() -john ThisworkislicensedunderaCreativeCommonsAttribution-NonCommercial-ShareAlike4.0InternationalLicense.PopularTopicsUbuntuLinuxBasicsJavaScriptReactPythonSecurityApacheMySQLDatabasesDockerKubernetesEbooksBrowsealltopictagsAlltutorialsQuestionsQ&AAskaquestionDigitalOceanProductDocsDigitalOceanSupportEventsTechTalksHacktoberfestDeployGetinvolvedCommunityNewsletterHollie'sHubforGoodWriteforDOnationsCommunitytoolsandintegrationsHatchStartupprogramJointheTechTalkSuccess!Thankyou!Pleasecheckyouremailforfurtherdetails.Pleasecompleteyourinformation!



請為這篇文章評分?