how to convert Python 2 unicode() function into correct Python ...

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

Long answer: In Python 3, Unicode was replaced with strings because of its abundance ... Chances are you can simply change the unicode() function to str() . 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 howtoconvertPython2unicode()functionintocorrectPython3.xsyntax AskQuestion Asked 6years,2monthsago Modified 3monthsago Viewed 42ktimes 28 IenabledthecompatibilitycheckinmyPythonIDEandnowIrealizethattheinheritedPython2.7codehasalotofcallstounicode()whicharenotallowedinPython3.x. IlookedatthedocsofPython2andfoundnohinthowtoupgrade: Idon'twanttoswitchtoPython3now,butmaybeinthefuture. Thecodecontainsabout500callstounicode() Howtoproceed? Update Thecommentofuservaultahtoreadthepyportingguidehasreceivedseveralupvotes. Mycurrentsolutionisthis(thankstoPeterBrittain): frombuiltinsimportstr ...Icouldnotfindthishintinthepyportingdocs..... pythonpython-3.xpython-unicode Share Improvethisquestion Follow editedOct1,2017at11:05 MartijnPieters♦ 989k275275goldbadges38913891silverbadges32473247bronzebadges askedAug1,2016at10:55 guettliguettli 23.8k6666goldbadges308308silverbadges587587bronzebadges 17 5 docs.python.org/3/howto/pyporting.html – vaultah Aug1,2016at10:57 @vaultahthisisnotageneralquestion.Itisonlyaboutunicode()calls.IthecodebasewhichIcurrentlyworkon,thereareabout700callstothismethod.WhatshouldIdo? – guettli Aug1,2016at13:57 3 Thereisnogoodanswertothisquestion.Ifyou'relucky,youcanjustremovethecallstounicodeandyou'regoodtogo.AllstringsareunicodeinPython3.Ifthisdoesnotwork,thenexpectlotsofwork.ThetransitionfromstrtounicodeliteralsandbytesisbyfarthemostincompatiblechangewhenswitchingfromPython2to3. – Phillip Aug3,2016at15:07 2 Couldn'tyoujustdefineyourownunicode()functionthatdoesnothingbutreturnstr(arg)inPython3? – martineau Aug3,2016at16:40 2 youcanassignstrtounicode-unicode=str(withoutparenthesis).Itshouldwork. – furas Aug3,2016at16:57  |  Show12morecomments 5Answers 5 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 28 +150 Ashasalreadybeenpointedoutinthecomments,thereisalreadyadviceonportingfrom2to3. Havingrecentlyhadtoportsomeofmyowncodefrom2to3andmaintaincompatibilityforeachfornow,Iwholeheartedlyrecommendusingpython-future,whichprovidesagreattooltohelpupdateyourcode(futurize)aswellasclearguidanceforhowtowritecross-compatiblecode. Inyourspecificcase,Iwouldsimplyconvertallcallstounicodetousestrandthenimportstrfrombuiltins.AnyIDEworthitssaltthesedayswilldothatglobalsearchandreplaceinoneoperation. Ofcourse,that'sthesortofthingfuturizeshouldcatchtoo,ifyoujustwanttouseautomaticconversion(andtolookforotherpotentialissuesinyourcode). Share Improvethisanswer Follow answeredAug3,2016at18:30 PeterBrittainPeterBrittain 13.3k33goldbadges4040silverbadges5454bronzebadges 4 1 Yes,futurizewillhelptransformthecodebase;unicode()callswillbetransformedtostr()callswithafrombuiltinsimportstrimportatthetop.Dotakeintoaccountthatgenerallydoesaddaninstall-typerequirementforthefuturelibraryonPython2(toprovidethebackportedbuiltinsmodule). – MartijnPieters ♦ Aug3,2016at19:22 1 thiswillbreaksqlalchemy,amongotherlibraries. – benw Jun20,2017at21:29 The"adviceonportingfrom2to3"mentionsunicodealot,butdoesn'treallymentiontheunicodefunctionitself. – cowlinator Sep20,2018at2:49 @cowlinatorThat'swhyIalsoreferencedthepythonfuturedocs.Seepython-future.org/compatible_idioms.html#unicode – PeterBrittain Sep20,2018at6:12 Addacomment  |  14 Youcantestwhetherthereissuchafunctionasunicode()intheversionofPythonthatyou'rerunning.Ifnot,youcancreateaunicode()aliasforthestr()function,whichdoesinPython3whatunicode()didinPython2,asallstringsareunicodeinPython3. #Python3compatibilityhack try: unicode('') exceptNameError: unicode=str Notethatamorecompleteportisprobablyabetteridea;seetheportingguidefordetails. Share Improvethisanswer Follow answeredAug3,2016at17:28 QuintQuint 1,0661212silverbadges1111bronzebadges 2 Yes,thishandmadesolutionshouldwork.ButIguessIwillusethefuturelibraryasexplainedintheanswerbyPeterBrittain. – guettli Aug4,2016at7:25 1 verysimpleanduseful,perfectsolutionfortheaskedquestion.also,noadditionaldependencies. – benzkji Aug31,2018at13:35 Addacomment  |  10 Shortanswer:Replaceallunicodecallswithstrcalls. Longanswer:InPython3,Unicodewasreplacedwithstringsbecauseofitsabundance.ThefollowingsolutionshouldworkifyouareonlyusingPython3: unicode=str #therestofyourgoesgoeshere IfyouareusingitwithbothPython2orPython3,usethisinstead: importsys ifsys.version_info.major==3: unicode=str #therestofyourcodegoeshere Theotherway:runthisinthecommandline $2to3package-w Share Improvethisanswer Follow editedSep27,2017at4:53 Graham 7,2131717goldbadges5858silverbadges8383bronzebadges answeredAug9,2016at21:20 user4913676user4913676 Addacomment  |  5 First,asastrategy,Iwouldtakeasmallpartofyourprogramandtrytoportit.Thenumberofunicodecallsyouaredescribingsuggesttomethatyourapplicationcaresaboutstringrepresentationsmorethanmostandeachuse-caseisoftendifferent. TheimportantconsiderationisthatallstringsareunicodeinPython3.Ifyouareusingthestrtypetostore"bytes"(forexample,iftheyarereadfromafile),thenyoushouldbeawarethatthosewillnotbebytesinPython3butwillbeunicodecharacterstobeginwith. Let'slookatafewcases. First,ifyoudonothaveanynon-ASCIIcharactersatallandreallyarenotusingtheUnicodecharacterset,itiseasy.Chancesareyoucansimplychangetheunicode()functiontostr().Thatwillassurethatanyobjectpassedasanargumentisproperlyconverted.However,itiswishfulthinkingtoassumeit'sthateasy. Mostlikely,you'llneedtolookattheargumenttounicode()toseewhatitis,anddeterminehowtotreatit. Forexample,ifyouarereadingUTF-8charactersfromafileinPython2andconvertingthemtoUnicodeyourcodewouldlooklikethis: data=open('somefile','r').read() udata=unicode(data) However,inPython3,read()returnsUnicodedatatobeginwith,andtheunicodedecodingmustbespecifiedwhenopeningthefile: udata=open('somefile','r',encoding='UTF-8').read() Asyoucansee,transformingunicode()simplywhenportingmaydependheavilyonhowandwhytheapplicationisdoingUnicodeconversions,wherethedatahascomefrom,andwhereitisgoingto. Python3bringsgreaterclaritytostringrepresentations,whichiswelcome,butcanmakeportingdaunting.Forexample,Python3hasaproperbytestype,andyouconvertbyte-datatounicodelikethis: udata=bytedata.decode('UTF-8') orconvertUnicodedatatocharacterformusingtheoppositetransform. bytedata=udata.encode('UTF-8') Ihopethisatleasthelpsdetermineastrategy. Share Improvethisanswer Follow answeredAug5,2016at6:01 GaryWisniewskiGaryWisniewski 1,0301010silverbadges99bronzebadges 1 Greatanswer,whichexplainstheimportanceofreplacingunicode()properly – AlastairMcCormack Aug6,2016at8:55 Addacomment  |  1 Youcanusesixlibrarywhichhavetext_typefunction(unicodeinpy2,strinpy3): fromsiximporttext_type Share Improvethisanswer Follow answeredJun20at16:40 AlexeyShrubAlexeyShrub 1,1101212silverbadges2020bronzebadges 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?Browseotherquestionstaggedpythonpython-3.xpython-unicodeoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Related 2927 HowdoIsplitalistintoequally-sizedchunks? 2557 HowdoIgetasubstringofastringinPython? 3058 HowdoImakefunctiondecoratorsandchainthemtogether? 3246 HowdoIconcatenatetwolistsinPython? 2573 HowtoupgradeallPythonpackageswithpip? 2898 HowdoIaccessenvironmentvariablesinPython? 2455 HowdoIlowercaseastringinPython? 3063 HowdoIdeleteafileorfolderinPython? 1347 BestwaytoconvertstringtobytesinPython3? 2646 HowcanIremoveakeyfromaPythondictionary? HotNetworkQuestions Whatprotocolisthiswaveform? Whyismyropeweird-looking? Howtodestroydatapermanentlyinaworldwheretimetraveliseasilydone? Canaphotonturnaprotonintoaneutron? Howtoformalizeagamewhereeachplayerisaprogramhavingaccesstoopponent'scode? WhathadEstherdonein"TheBellJar"bySylviaPlath? AmIreallyrequiredtosetupanInheritedIRA? Howdocucumbershappen?Whatdoes"verypoorlypollinatedcucumber"meanexactly?Howcanpollinationbe"uneven"? PacifistethosblockingmyprogressinStellaris Interpretinganegativeself-evaluationofahighperformer Whataretheargumentsforrevengeandretribution? Vivadoconstraintswizardsuggestsalotofnonsensegeneratedclocks SomeoneofferedtaxdeductibledonationasapaymentmethodforsomethingIamselling.AmIgettingscammed? Botchingcrosswindlandings HowtogetridofUbuntuProadvertisementwhenupdatingapt? WhatdothecolorsindicateonthisKC135tankerboom? StandardCoverflow-safearithmeticfunctions Justifyingdefinitionsofagroupaction. IfthedrowshadowbladeusesShadowSwordasarangedattack,doesitthrowasword(thatitthenhastoretrievebeforeusingitagain)? Whydoes«facture»mean"bill,invoice"? HowcanIkeepmyampfromtemperingthetoneofmyprocessor?(rockandhardmetalmusic) Single-rowSettingstable:prosandconsofJoinsvsscalarsubqueries Whatistheconventionalwaytonotateameterwithaccentsoneverysecond8thnote? tutorialto"motionblur"peopleonbackground morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?