How to make unicode string with python3 - Stack Overflow
文章推薦指數: 80 %
Fix Python 2.x. try: UNICODE_EXISTS = bool(type(unicode)) except ... Moment Caf\\u00E8 in St.Augustine\\u2764\\uFE0F\\u2764\\uFE0F ' import codecs new_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 Howtomakeunicodestringwithpython3 AskQuestion Asked 11years,2monthsago Modified 7monthsago Viewed 250ktimes 120 Iusedthis: u=unicode(text,'utf-8') ButgettingerrorwithPython3(or...maybeIjustforgottoincludesomething): NameError:globalname'unicode'isnotdefined Thankyou. pythonunicodepython-3.x Share Improvethisquestion Follow editedJul25,2011at6:46 buruzaemon 3,79111goldbadge2121silverbadges4444bronzebadges askedJul25,2011at5:16 cndcnd 31.4k6161goldbadges176176silverbadges305305bronzebadges 2 18 Ifthere'sanawesomereasontoupgradetopython3itisunicodebydefault. – JBernardo Jul25,2011at5:49 text.encode('unicode_escape')wouldbeenoughIguess – Ritwik Sep5,2021at16:10 Addacomment | 6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 161 LiteralstringsareunicodebydefaultinPython3. Assumingthattextisabytesobject,justusetext.decode('utf-8') unicodeofPython2isequivalenttostrinPython3,soyoucanalsowrite: str(text,'utf-8') ifyouprefer. Share Improvethisanswer Follow editedMar7,2019at10:20 IanS 15.2k99goldbadges5757silverbadges8181bronzebadges answeredJul25,2011at5:21 JohnLaRooyJohnLaRooy 286k5151goldbadges359359silverbadges499499bronzebadges 4 70 TypeError:decodingstrisnotsupported – Gank Apr18,2016at13:49 13 @Gank,InPython3astrisunicode,ie.itis"decoded"soitmakesnosensetocalldecodeonit – JohnLaRooy Apr19,2016at9:43 1 SameTypeError.Pleasejustreplacewithstr(txt),orthecodefrom@magicrebirthbelow – Simon Oct28,2017at18:37 5 Theoriginalsampleisnotclear.Soinpython3,ifyouwanttodostr(text,'utf-8'),textmustbeastringbinary.e.g.str(b'thisisabinary','utf-8') – killua8p Aug22,2018at4:13 Addacomment | 12 What'snewinPython3.0says: AlltextisUnicode;howeverencodedUnicodeisrepresentedasbinary data Ifyouwanttoensureyouareoutputtingutf-8,here'sanexamplefromthispageonunicodein3.0: b'\x80abc'.decode("utf-8","strict") Share Improvethisanswer Follow answeredJul25,2011at5:25 TremmorsTremmors 2,8881616silverbadges1313bronzebadges 1 1 thisisexactlywhatweneedfor'\x80abc'.decode("utf-8","strict")inPython2,thanks – http8086 Jan2,2017at3:31 Addacomment | 9 Asaworkaround,I'vebeenusingthis: #FixPython2.x. try: UNICODE_EXISTS=bool(type(unicode)) exceptNameError: unicode=lambdas:str(s) Share Improvethisanswer Follow answeredJul6,2016at16:06 magicrebirthmagicrebirth 3,85622goldbadges2323silverbadges2222bronzebadges 3 12 Whyareyouusingalambdafunction?Thesemethodsarecalledthesamewayinanycase.Thisisasimplervariation:try:unicode=str;except:pass. – nicbou Oct25,2017at10:02 1 Itseemslikeyoucanjustdounicode=strsinceitwon'tfailineither2or3 – Nickolai May25,2018at22:23 1 OrfromsiximportuasunicodewhichI'dprefersimplybecauseit'smoreself-documenting(sincesixisa2/3compatibilitylayer)thanunicode=str – Nickolai May25,2018at22:25 Addacomment | 5 ThishowIsolvedmyproblemtoconvertcharslike\uFE0F,\u000A,etc.Andalsoemojisthatencodedwith16bytes. example='rawveganchocolatecocoapiewchocolate&vanillacream\\uD83D\\uDE0D\\uD83D\\uDE0D\\u2764\\uFE0FPresentMomentCaf\\u00E8inSt.Augustine\\u2764\\uFE0F\\u2764\\uFE0F' importcodecs new_str=codecs.unicode_escape_decode(example)[0] print(new_str) >>>'rawveganchocolatecocoapiewchocolate&vanillacream\ud83d\ude0d\ud83d\ude0d❤️PresentMomentCafèinSt.Augustine❤️❤️' new_new_str=new_str.encode('utf-16',errors='surrogatepass').decode('utf-16') print(new_new_str) >>>'rawveganchocolatecocoapiewchocolate&vanillacream😍😍❤️PresentMomentCafèinSt.Augustine❤️❤️' Share Improvethisanswer Follow editedFeb17at16:48 OskarAustegard 4,54144goldbadges3535silverbadges5050bronzebadges answeredAug26,2019at15:22 IlyasIlyas 1,7181414silverbadges99bronzebadges 1 Formoreon'surrogatepass'seedocs.python.org/3/library/codecs.html#error-handlers – OskarAustegard Feb17at16:48 Addacomment | 0 theeasiestwayinpython3.x text="hi,I'mtext" text.encode('utf-8') Share Improvethisanswer Follow answeredJul15,2019at6:08 mosi_khamosi_kha 46055silverbadges77bronzebadges Addacomment | -1 InaPython2programthatIusedformanyyearstherewasthisline: ocd[i].namn=unicode(a[:b],'utf-8') ThisdidnotworkinPython3. However,theprogramturnedouttoworkwith: ocd[i].namn=a[:b] Idon'trememberwhyIputunicodethereinthefirstplace,butIthinkitwasbecausethenamecancontainsSwedishlettersåäöÅÄÖ.Buteventheyworkwithout"unicode". Share Improvethisanswer Follow editedMay10,2019at10:02 cezar 11.2k66goldbadges4343silverbadges8181bronzebadges answeredMar28,2019at12:15 PerPerssonPerPersson 15511goldbadge11silverbadge66bronzebadges 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?Browseotherquestionstaggedpythonunicodepython-3.xoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Linked -2 StringtoUnicodeshowingerror:name'unicode'isnotdefined 709 Whatisthebestwaytoremoveaccents(normalize)inaPythonunicodestring? 4 Howtoconvertlisttounicodelist 7 Python3srcencodingsofEmojis 1 unicodepython3equivalent 1 howtocheckifaninputiseitherastringorunicodeinpython 1 'utf-8'codecerrorwhiledoc2vec 0 unicodeinpython3givesNameError:globalname'unicode'isnotdefined 0 encodinginstringsindataframenotrecognizedinPython 0 Convertinginconsistantencodingtoutf-8Python3.4BS4.3 Seemorelinkedquestions Related 6474 HowdoImergetwodictionariesinasingleexpression? 6784 HowdoIcheckwhetherafileexistswithoutexceptions? 3469 Convertbytestoastring 4855 HowdoImakeaflatlistoutofalistoflists? 3218 "LeastAstonishment"andtheMutableDefaultArgument 1673 ProperwaytodeclarecustomexceptionsinmodernPython? 1247 Whatdoesthe'b'characterdoinfrontofastringliteral? 2112 WhyisreadinglinesfromstdinmuchslowerinC++thanPython? 1454 UnicodeEncodeError:'ascii'codeccan'tencodecharacteru'\xa0'inposition20:ordinalnotinrange(128) 1822 HowdoIsplitthedefinitionofalongstringovermultiplelines? HotNetworkQuestions Whydostringhashcodeschangeforeachexecutionin.NET? PacifistethosblockingmyprogressinStellaris Isitcorrecttochangetheverbto"being"in"Despitenoonewashurtinthisincident…"? Whataretheargumentsforrevengeandretribution? Whydoesn'ttheMBRS1100SchottkydiodehaveanexponentialI/Vcharacteristic? WhyareRussiancombatantsinUkraineconsideredsoldiersratherthanterrorists? Could"nocloning"beusedasadefenceforquantumencryption? Interpretinganegativeself-evaluationofahighperformer Howtotellifmybikehasanaluminumframe Howdocucumbershappen?Whatdoes"verypoorlypollinatedcucumber"meanexactly?Howcanpollinationbe"uneven"? WhydidGodprohibitwearingofgarmentsofdifferentmaterialsinLeviticus19:19? WhytheneedforaScienceOfficeronacargovessel? Howtoproperlycolorcellsinalatextablewithoutscrewingupthelines? Findanddeletepartiallyduplicatelines Howcanmyaliensymbiotesidentifyeachother? IsdocumentingabigprojectwithUMLDiagramsneeded,goodtohaveorevennotpossible? WhydopeopleinsistonusingTikzwhentheycanusesimplerdrawingtools? Whatistheconventionalwaytonotateameterwithaccentsoneverysecond8thnote? Sortbycolumngroupandignoreothercolumnsfailingforthisexample,why? MakeaCourtTranscriber HowdoGPSreceiverscommunicatewithsatellites? Whatisthebestwaytocalculatetruepasswordentropyforhumancreatedpasswords? CounterexampleforChvatal'sconjectureinaninfiniteset DidMS-DOSeverdropabilitytosupportnon-IBMPCcompatiblemachines? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Python 3 Tutorial 第二堂(1)Unicode 支援、基本I/O
是這樣的… import sys for line in open(sys.
- 2Unicode 指南— Python 3.10.7 說明文件
还有有关显示的属性,比如如何在双向文本中使用码位。 以下程序显示了几个字符的信息,并打印一个字符的数值:. import unicodedata ...
- 3Unicode in Python 2
Unicode strings are sequences of platonic characters ... import codecs codecs.encode() codecs.dec...
- 4Unicode — pysheeet
In Python 3, strings are represented by Unicode instead of bytes. ... get u2 byte string b'Cafe\x...
- 5How to make unicode string with python3 - Stack Overflow
Fix Python 2.x. try: UNICODE_EXISTS = bool(type(unicode)) except ... Moment Caf\\u00E8 in St.Augu...