What's the u prefix in a Python string? - Stack Overflow
文章推薦指數: 80 %
The u in u'Some String' means that your string is a Unicode string. Q: ... 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 What'stheuprefixinaPythonstring? AskQuestion Asked 12years,7monthsago Modified 11monthsago Viewed 287ktimes 306 Likein: u'Hello' Myguessisthatitindicates"Unicode",isthatcorrect? Ifso,sincewhenhasitbeenavailable? pythonsyntax Share Improvethisquestion Follow editedOct19,2021at16:51 OscarRyz askedMar17,2010at18:43 OscarRyzOscarRyz 193k110110goldbadges378378silverbadges563563bronzebadges 0 Addacomment | 5Answers 5 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 216 You'reright,see3.1.3.UnicodeStrings. It'sbeenthesyntaxsincePython2.0. Python3madethemredundant,asthedefaultstringtypeisUnicode.Versions3.0through3.2removedthem,buttheywerere-addedin3.3+forcompatibilitywithPython2toaidethe2to3transition. Share Improvethisanswer Follow editedApr23,2019at21:22 NickT 24.7k1111goldbadges7878silverbadges118118bronzebadges answeredMar17,2010at18:45 StefanKendallStefanKendall 64.7k6666goldbadges247247silverbadges402402bronzebadges 1 1 Combiningunicode+raw(regex)strings(e.g.ur"string")isvalidinPython2,butitisunfortunatelyinvalidsyntaxinPython3. – cowlinator Feb18,2020at9:07 Addacomment | 150 Theuinu'SomeString'meansthatyourstringisaUnicodestring. Q:I'minaterrible,awfulhurryandIlandedherefromGoogleSearch.I'mtryingtowritethisdatatoafile,I'mgettinganerror,andIneedthedeadsimplest,probablyflawed,solutionthissecond. A:YoushouldreallyreadJoel'sAbsoluteMinimumEverySoftwareDeveloperAbsolutely,PositivelyMustKnowAboutUnicodeandCharacterSets(NoExcuses!)essayoncharactersets. Q:srynotimecodepls A:Fine.trystr('SomeString')or'SomeString'.encode('ascii','ignore').ButyoushouldreallyreadsomeoftheanswersanddiscussiononConvertingaUnicodestringandthisexcellent,excellent,primeroncharacterencoding. Share Improvethisanswer Follow editedOct9,2017at18:56 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges answeredMay24,2013at18:55 AndrewAndrew 8,86088goldbadges4444silverbadges5858bronzebadges 4 7 ThisworksifthestringcontainsASCIItextonly.Inallothercasesyou'llhavetoexplicitlyencode. – MartijnPieters ♦ Sep13,2014at13:55 3 Thistreatstheu''assomething"togetridof".Thistellsmethatyoudon'tactuallyunderstandwhatitis.Yougenerallydonotjustwantto"getridof"it,andthecorrectwaytomakeabytestringfromaUnicodestringdependsonwhatthatstringcontainsandinwhichcontext. – LennartRegebro Dec9,2014at12:32 3 @LennartRegebrototallyagreed-thiswasathrowawayanswerthatwasmeanttobetongueincheek,butitaccumulatedasortofhorrifyingnumberofupvotes.editedtotrytosteerfolksintherightdirection. – Andrew Feb5,2015at22:28 2 Thatwasafunread!Thanks!Articleis17yearsoldandit'sstillaccurate.Wow. – KerwinSneijders Feb28,2020at11:08 Addacomment | 54 Myguessisthatitindicates"Unicode",isitcorrect? Yes. Ifso,sincewhenisitavailable? Python2.x. InPython3.xthestringsuseUnicodebydefaultandthere'snoneedfortheuprefix.Note:inPython3.0-3.2,theuisasyntaxerror.InPython3.3+it'slegalagaintomakeiteasiertowrite2/3compatibleapps. Share Improvethisanswer Follow editedMar26,2018at17:39 Jacinda 4,77222goldbadges2525silverbadges3737bronzebadges answeredMar17,2010at18:45 kennytmkennytm 498k101101goldbadges10621062silverbadges994994bronzebadges 5 4 It'sevenaSyntaxErrorinPython3tousetheuprefix. – TimPietzcker Mar17,2010at18:53 14 @TimPietzcker:Onlyin3.0-3.2;in3.3+it'slegal(andmeaningless),tomakeiteasiertowrite2.6+/3.3+single-codebaselibrariesandapps. – abarnert Sep11,2014at23:59 @abarnert:Well,thatcommentisnowfour-and-a-halfyearsold:) – TimPietzcker Sep12,2014at7:59 3 @TimPietzcker:Sure,butjustasyourcommentwasausefuladdendumforanyonefindingthisusefulanswerbysearchin2010,Ithinkit'susefultomentionthechangein3.3toanyonefindingitin2014.Itmightarguablybebettertoedittheanswer,butIthinkit'saminorpointthatmostpeoplewon'truninto(becauseunlessyou'restillusing3.0-3.2in2014,"noneedfortheprefix"isallyouneedtoknow). – abarnert Sep12,2014at17:36 Ifyou'rewritingcodeforarbitraryuserstodownloadandrun,andwanttocoverthemostpossiblecaseswithoutmakingassumptions,it'shelpfultoknow3.0-3.2willbreak.Becauseyouneedtodecideifyoucaretousesix.text_type()everywhereforthe(hopefullyminiscule)numberofpeoplestillusing3.[012]-atleasttheinformationistheresoyoucanchoose. – dwanderson Aug22,2018at0:31 Addacomment | 6 IcameherebecauseIhadfunny-char-syndromeonmyrequestsoutput.Ithoughtresponse.textwouldgivemeaproperlydecodedstring,butintheoutputIfoundfunnydouble-charswhereGermanumlautsshouldhavebeen. Turnsoutresponse.encodingwasemptysomehowandsoresponsedidnotknowhowtoproperlydecodethecontentandjusttreateditasASCII(Iguess). Mysolutionwastogettherawbyteswith'response.content'andmanuallyapplydecode('utf_8')toit.TheresultwasschöneUmlaute. Thecorrectlydecoded für vs.theimproperlydecoded fĂźr Share Improvethisanswer Follow editedJul18,2019at9:36 answeredNov14,2017at16:14 ChrisChris 5,26444goldbadges2828silverbadges3636bronzebadges Addacomment | 2 Allstringsmeantforhumansshoulduseu"". IfoundthatthefollowingmindsethelpsalotwhendealingwithPythonstrings:AllPythonmanifeststringsshouldusetheu""syntax.The""syntaxisforbytearrays,only. Beforethebashingbegins,letmeexplain.MostPythonprogramsstartoutwithusing""forstrings.ButthentheyneedtosupportdocumentationofftheInternet,sotheystartusing"".decodeandallofasuddentheyaregettingexceptionseverywhereaboutdecodingthisandthat-allbecauseoftheuseof""forstrings.Inthiscase,Unicodedoesactlikeavirusandwillwreakhavoc. But,ifyoufollowmyrule,youwon'thavethisinfection(becauseyouwillalreadybeinfected). Share Improvethisanswer Follow editedOct9,2017at18:54 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges answeredMar17,2010at18:51 FrankKruegerFrankKrueger 68.1k4646goldbadges161161silverbadges207207bronzebadges 3 bash-c"echoShouldn\\'tyouuseb\\\"...\\\"forbytearrays?" – kennytm Mar17,2010at19:06 @KennyTMSoundsgood!Simplymeanttosayallstringsmeantforhumansshoulduseu"". – FrankKrueger Mar17,2010at19:38 1 IfyouwanttoreligiouslyuseUnicodeeverywhere—which,formanyapplications(butnotall),isagoodthing—youalmostcertainlywantPython3.x,not2.x.Thatmaynothavebeentruein2010whenthiswaswritten,butin2014,mostlibrariesorplatformsthatpreventyoufromupgradingto3.xwillalsopreventyoufromusingUnicodeproperly… – abarnert Sep12,2014at0:01 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?Browseotherquestionstaggedpythonsyntaxoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Linked 135 Whatdoesthe'u'symbolmeaninfrontofstringvalues? 2 Whyistherea'u'beforeeverylineofmyoutput? 0 Whyisanewcharacter'u'gettingaddedwhenIexecutethePythonscript? 2 Whatisthe"u"inresults(Python)? 1 extracharactersonpythonlist 0 Convertinglistofstringswithu'...'toalistofnormalstrings 1 ConvertingJSONtoPythonDictionariesreplacesdoublequoteswithsingleandaddsa"u"beforeeachdoublequoteopeninginstance -3 Howtodelete"u'"beforetheattributes -1 WhyunicodeliteralisneededifstringisunicodeinPython3? -1 PythonNewsList Seemorelinkedquestions Related 6975 WhataremetaclassesinPython? 12290 Whatdoesthe"yield"keyworddo? 7492 DoesPythonhaveaternaryconditionaloperator? 4865 Accessingtheindexin'for'loops 3218 "LeastAstonishment"andtheMutableDefaultArgument 8278 Whatdoes"usestrict"doinJavaScript,andwhatisthereasoningbehindit? 3588 DoesPythonhaveastring'contains'substringmethod? 3334 HowtoconcatenatestringvariablesinBash 3585 Catchmultipleexceptionsinoneline(exceptblock) 1845 Whydoes++[[]][+[]]+[+[]]returnthestring"10"? HotNetworkQuestions AreChernclasseswelldefineduptocontractiblechoice? Howtoformalizeagamewhereeachplayerisaprogramhavingaccesstoopponent'scode? Howtotellifmybikehasanaluminumframe Whatprotocolisthiswaveform? What'sthemeaningoftheerrorproto.014-PtKathma.tez.subtraction_underflow? Howdouncomputablenumbersrelatetouncomputablefunctions? LaTeX2(e)vsLaTeX3 Whatdoyoucallastatementthatisgivenasanexplanationwhysomeonehaswonanaward? Single-rowSettingstable:prosandconsofJoinsvsscalarsubqueries Movingframesmethod Isthe2...g6DutchautomaticallywinningforWhite? WhyareRussiancombatantsinUkraineconsideredsoldiersratherthanterrorists? What'sthedifferencebetween'Dynamic','Random',and'Procedural'generations? CanIuseaspritesheetfromanexistingvideogameformypromotionalreel? Canyoufindit? Wordsforrestaurant Howtodestroydatapermanentlyinaworldwheretimetraveliseasilydone? PacifistethosblockingmyprogressinStellaris Findanddeletepartiallyduplicatelines Doublelinemathsentence Whyistherealotofcurrentvariationattheoutputofabuckwhenabatteryisconnectedattheoutput? Iwanttodothedoubleslitexperimentwithelectrons,but ReturnoftheJedi-"northtower"-howcanyoutellthecardinalpointsincenterofasphere? Howdoyoucalculatethetimeuntilthesteady-stateofadrug? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1What's the u prefix in a Python string? - Stack Overflow
The u in u'Some String' means that your string is a Unicode string. Q: ...
- 2Python What Does 'u' Mean in Front of a String - codingem.com
The 'u' in front of a string means the string is a Unicode string. A Unicode is a way for a strin...
- 3python中將\\uxxxx轉換為Unicode字串的方法- IT閱讀
這篇文章主要介紹了python中將\\uxxxx轉換為Unicode字串的方法,小編覺得挺不錯的, ... return _compile(pattern, flags).sub(repl, s...
- 4Unicode HOWTO — Python 3.10.7 documentation
A Unicode string is turned into a sequence of bytes that contains embedded zero bytes only where ...
- 5Python——str字符串和unicode字符串_Vic时代的博客
对于处理过中文的Python程序员来说,想必被UnicodeEncodeError和UnicodeDecodeError并不陌生。为了更好的理解Python中的编码问题,我们首先介绍一下 ...