This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4).
Really my goal here is just to successfully make type(value) return unicode. I found an earlier question that had some useful information, but the example from the picked answer doesn't seem to run for me. Is there something I am doing wrong here?
Here is some code to reproduce:
Name = 'w\xc3\xb6rner'.decode('utf-8')
file.write('Name: %s - %s\n' %(Name, type(Name)))
I never actually get to the write statement, because it fails on the first statement.
Thank you for your help.
Edit:
I verified that the DB's charset is utf8. So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs. Is there a difference between 'utf-8' and 'utf8'?
The tip on using codecs to write to a file is handy (I'll definitely use it), but in this scenario I am only writing to a log file for debugging purposes.
Your string is not in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly:
print 'w\xf6rner'.decode('cp1250')
EDIT
For writing unicode strings to the file you can use codecs module:
import codecs
f = codecs.open("yourfile.txt", "w", "utf8")
f.write( ... )
It is handy to specify encoding of the input/output and using 'unicode' string throughout your code without bothering of different encodings.
It's obviously 1-byte encoding. 'ö' in UTF-8 is '\xc3\xb6'.
The encoding might be:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With