Is there a difference between String.encode and codecs ...
文章推薦指數: 80 %
encode.. does it matter which one i use ? I'm just specifying the encoding i need in the encode function. Also, when reading this thread python ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams IsthereadifferencebetweenString.encodeandcodecs.encode? AskQuestion Asked 7years,7monthsago Modified 1year,7monthsago Viewed 3ktimes 2 Whenreadingaboutcodecs,encodinganddecodingIfoundthatishouldusetheencodefunctiononthestringdirectlyandthatworkedfine.I'veafterthatreadaboutwhattheunicodeandasciiisinadditiontothedifferentutfencodings. Butwhenreadingfurtherifoundthatmostpeopleseemtoimportthecodecsmoduleanduseencodefromthemodule.IdontseemuchofadifferencebetweenString.encodeandcodecs.encode..doesitmatterwhichoneiuse?I'mjustspecifyingtheencodingineedintheencodefunction. Also,whenreadingthisthreadpythonstringencode/decodeilookedatthelinkintheacceptedanswerwhichshowsaslideshowwhichissupposeto"completelydemystifyunicodeandutf"butononeoftheslideshesaysthatutfisusedtotranslatenumberstocharacterswhichicantseeiscorrect. Frommyunderstandingbasedonhttp://www.rrn.dk/the-difference-between-utf-8-and-unicodewhichwasalsoquotedinanotherSOthreadutfisnottranslatingnumberstocharacters.Itstranslatingbinarynumberstonumbersfoundintheunicodeortheotherchoosencharactersetbeingused.Soutfwouldbetranslationofabinarynumbertoanumberandthenunicodewouldbetranslatingthatnumberagaintoacharacter..sohegotitwrongwhentryingtocompletelymystifythis? pythonunicodeencodingutf-8character-encoding Share Improvethisquestion Follow editedMay23,2017at12:12 CommunityBot 111silverbadge askedMar1,2015at15:25 exceedexceed 44966silverbadges1616bronzebadges 4 Doyoumeanstr.encode()? – KSFT Mar1,2015at15:27 @KSFTyesitshouldbestr.encode()andnotString.encode – exceed Mar1,2015at15:58 Didyouseemyanswer? – KSFT Mar1,2015at16:31 Yes,iguesstheyareprettymuchthesamebutseemslikecodecsaremoreflexibleasitcantakeanobject..itdoesntseemtobeclearfromthedocsbutmaybeitalsocandoothertypesofencodingthanjusttextaswellmhm.Ididntreplytoyouranswerbecauseididntreallyseethatitofferedananswertothequestionasthereprobablyshouldbeareasonforittohavetwodifferentfunctionsbutiguesssincecodecs.encodecantakeanobjectitsmoreflexible – exceed Mar1,2015at16:59 Addacomment | 3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 2 ThePythondocpagesforthesetwofunctionsarehere: https://docs.python.org/2/library/stdtypes.html#str.encode https://docs.python.org/2/library/codecs.html#codecs.encode str.encode()iscalledonastringobjectlikethis: "thisisastring".encode() codecs.encode()iscalledwithastringasanargumentlikethis: codecs.encode("thisisastring") Theyeachtakeanoptionalencodingargument. str.encode()'sdefaultencodingisthecurrentdefault,accordingtothedocpage,butaccordingthetheUnicodeHOWTO,that's"ascii" codecs.encode()'sdefaultencodingis"ascii" Bothfunctionstakeanerrorsargumentthatdefaultsto"strict". Itlookslikethey'reprettymuchthesameexceptforthewaythey'recalled. Share Improvethisanswer Follow answeredMar1,2015at15:37 KSFTKSFT 1,7541010silverbadges1717bronzebadges Addacomment | 1 codecs.encode(obj,encoding='utf-8',errors='strict') encodetexttobytes,texttotext,andbytestobytes str.encode(encoding="utf-8",errors="strict") encodetexttobytes so,Ithink2.⊆1. Share Improvethisanswer Follow editedJan15,2019at8:53 jpeg 2,24244goldbadges1818silverbadges3030bronzebadges answeredJan15,2019at8:00 RobotmangoRobotmango 1111bronzebadge Addacomment | 1 Onedifferenceiswhatcodecsyoucanuse.str.encodeisfineforcastingamongstringcodecs,buttryconvertingastringtobase64. str.encode("base64") LookupError:'base64'isnotatextencoding;usecodecs.encode()tohandlearbitrarycodecs butthiswillwork codecs.encode(str.encode(),"base64") orthis base64.encodestring(str.encode()) Share Improvethisanswer Follow answeredFeb15,2021at1:20 TaraTara 1111bronzebadge Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonunicodeencodingutf-8character-encodingoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Visitchat Linked 55 stringencodinganddecoding? Related 4405 Differencebetween@staticmethodand@classmethod 3113 WhatisthedifferencebetweenPython'slistmethodsappendandextend? 609 UTF-8,UTF-16,andUTF-32 674 WhatisthedifferencebetweenUTF-8andUnicode? 1251 What'sthedifferencebetweenutf8_general_ciandutf8_unicode_ci? 3475 Whatisthedifferencebetween__str__and__repr__? 974 What'sthedifferencebetweenUTF-8andUTF-8withBOM? 585 WhydoesmodernPerlavoidUTF-8bydefault? 1247 Whatdoesthe'b'characterdoinfrontofastringliteral? 1454 UnicodeEncodeError:'ascii'codeccan'tencodecharacteru'\xa0'inposition20:ordinalnotinrange(128) HotNetworkQuestions Whydoes«facture»mean"bill,invoice"? DoestheDemocraticPartyofficiallysupportrepealingtheSecondAmendment? Howdoparty-listsystemsaccommodateindependentcandidates? SomeoneofferedtaxdeductibledonationasapaymentmethodforsomethingIamselling.AmIgettingscammed? Sciencefictionbook/novelaboutaliensinhumans'bodies Writingthenumber'80668227'asasumsof4&5cubes Whywouldanearfuturesocietystruggletogrowcropsonalargelevel? Alternativeversionsofbreathing? WhytheneedforaScienceOfficeronacargovessel? LaTeX2(e)vsLaTeX3 MLmodellingwheretheoutputaffectstheDGP Myfavoriteanimalisa-singularandpluralform Whydoesn'ttheMBRS1100SchottkydiodehaveanexponentialI/Vcharacteristic? CounterexampleforChvatal'sconjectureinaninfiniteset Whyarefighterjetssoloudwhendoingslowflight? WhydopeopleinsistonusingTikzwhentheycanusesimplerdrawingtools? Howdocucumbershappen?Whatdoes"verypoorlypollinatedcucumber"meanexactly?Howcanpollinationbe"uneven"? Areyougettingtiredofregularcrosswords? Unsurewhatthesewatersoftenerdialsarefor Doesindecentexposurerequireintentionality? Whyare"eat"and"drink"differentwordsinlanguages? StandardCoverflow-safearithmeticfunctions Checkingregionmembershipinapolygondefinedbycomplexroots Howtotellifmybikehasanaluminumframe morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Python Examples of codecs.open - ProgramCreek.com
This page shows Python examples of codecs.open. ... def loadFile(fName): word=[]; import codecs; ...
- 2Python codecs.encode() Examples - ProgramCreek.com
This page shows Python examples of codecs.encode.
- 3Is there a difference between String.encode and codecs ...
encode.. does it matter which one i use ? I'm just specifying the encoding i need in the encode f...
- 4Codecs - Core API - Python Client
Using a codec. All the codecs provided by the coreapi library are instantiated without arguments,...
- 5Python Codecs Open | Delft Stack