Python ASCII and Unicode decode error - Stack Overflow
文章推薦指數: 80 %
Getting a decoding error when encoding seems like your string is not unicode. In this case IIRC python will automaticall do: ...
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
PythonASCIIandUnicodedecodeerror
AskQuestion
Asked
10years,2monthsago
Modified
4years,4monthsago
Viewed
58ktimes
13
Igotthisveryveryfrustratingerrorwheninsertingacertainstringintomydatabase.Itsaidsomethinglike:
Pythoncannotdecodebytecharacters,expectingunicode"
Afteralotofsearching,IsawthatIcouldovercomethiserrorbyencodingmystringintoUnicode.ItrytodothisbydecodingthestringfirstandthenencodingitinUTF-8format.Like:
string=string.encode("utf8")
AndIgetthefollowingerror:
'ascii'codeccan'tdecodebyte0xe3inposition6:ordinalnotinrange(128)
Ihavebeendyingwiththiserror!HowdoIfixit?
pythonstringsqlitecharacter-encoding
Share
Follow
editedJul21,2012at18:25
PeterMortensen
30.6k2121goldbadges102102silverbadges124124bronzebadges
askedJul18,2012at15:09
AmitashAmitash
1,01366goldbadges1616silverbadges2626bronzebadges
2
1
There'snowaywe'llbeabletoprovidespecificsifyoudon'tshowactualcode.
– NedBatchelder
Jul18,2012at15:13
3
showusthestring(maybeevenviarepr(string)).Gettingadecodingerrorwhenencodingseemslikeyourstringisnotunicode.InthiscaseIIRCpythonwillautomaticalldo:string.decode("ascii").encode("utf-8").Showussomesamplestringsandasamplecodetoreproducetheproblem.
– javex
Jul18,2012at15:16
Addacomment
|
5Answers
5
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
50
Youneedtotakeadisciplinedapproach.PragmaticUnicode,orHowDoIStopThePain?haseverythingyouneed.
Ifyougetthaterroronthatlineofcode,thentheproblemisthatstringisabytestring,andPython2isimplicitlytryingtodecodeittoUnicodeforyou.Butitisn'tpureascii.Youneedtoknowwhattheencodingis,anddecodeitproperly.
Share
Follow
editedJun13,2014at1:25
MichaelKohne
11.7k33goldbadges4646silverbadges7575bronzebadges
answeredJul18,2012at15:12
NedBatchelderNedBatchelder
352k7171goldbadges552552silverbadges650650bronzebadges
3
7
Youmayalsoneedtoreadthisfirst:TheAbsoluteMinimumEverySoftwareDeveloperAbsolutely,PositivelyMustKnowAboutUnicodeandCharacterSetsjoelonsoftware.com/articles/Unicode.html
– spookylukey
Jul19,2012at11:26
@spookylukeyThatarticleisprettyoutdated.Inoticed.InUTF-8,everycodepointfrom0-127isstoredinasinglebyte.Onlycodepoints128andabovearestoredusing2,3,infact,upto6bytes..Itwasrestrictedto4bytes9yearsago.Isthereasimilararticlebutmoreup-to-date?
– Esailija
Jul21,2012at14:47
2
@Esailija:thatpointisminor,andtherearetechnicalreasonswhy"6bytes"isalsoaccurate.Everythingelseaboutthearticleisgood.
– NedBatchelder
Jul21,2012at18:41
Addacomment
|
12
Theencodemethodshouldbeusedonunicodeobjectstoconvertthemtoastrobjectwithagivenencoding.Thedecodemethodshouldbeusedonstrobjectsofagivenencodingtoconvertthemunicodeobjects.
IsupposethatyourdatabasestorestringsinUTF-8.Sowhenyougetstringsfromthedatabase,convertthemtounicodeobjectsbydoingstr.decode('utf-8').Thenonlyuseunicodeobjectsinyourpythonprogram(literalsaredefinedwithu'unicodestring').Andjustbeforestoringtheminyourdatabase,convertthemtostrobjectswithuni.encode('utf-8').
Share
Follow
answeredJul18,2012at15:15
SylvainDefresneSylvainDefresne
40.9k1111goldbadges7373silverbadges8383bronzebadges
Addacomment
|
5
EDIT:Asyoucanseefromthedownvotes,thisisNOTTHEBESTWAYTODOIT.Anexcellent,andahighlyrecommendedanswerisimmediatelyafterthis,soifyouarelookingforagoodsolution,pleaseusethat.Thisisahackishsolutionthatwillnotbekindtoyouatalaterpointoftime.
Ifeelyourpain,I'vehadalotofproblemswiththesameerror.ThesimplestwayIsolvedit(andthismightnotbethebestway,anditdependsonyourapplication)wastoconvertthingstounicode,andignoreerrors.Here'sanexamplefromUnicodeHOWTO-Pythonv2.7.3documentation
>>>unicode('\x80abc',errors='strict')
Traceback(mostrecentcalllast):
File"
延伸文章資訊
- 1python decode errors参数_Garb_v2的博客 - CSDN博客
decode的函数原型是decode([encoding], [errors='strict']),可以用第二个参数控制错误处理的策略,默认的参数就是strict,代表遇到非法字符时抛出 ...
- 2UnicodeError雜談之三———快點投靠python3啦啦啦 - iT 邦幫忙
python UnicodeError雜談之三囉唆一下:跟昨天的囉唆一樣, ... self.errors, final) UnicodeDecodeError: 'utf-8' codec c...
- 3Python decode()方法 - 菜鸟教程
Python decode() 方法以encoding 指定的编码格式解码字符串。默认编码为字符串编码。 语法. decode()方法语法: str.decode(encoding='UTF-8...
- 4Python中解码decode()与编码encode()与错误处理 ... - 博客园
errors may be given to set a different error handling scheme. The default for errors is 'strict' ...
- 5Python ASCII and Unicode decode error - Stack Overflow
Getting a decoding error when encoding seems like your string is not unicode. In this case IIRC p...