Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
The u in
u'Some String'
means that your string is a
Unicode string
.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's
Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
essay on character sets.
Q: sry no time code pls
A: Fine. try
str('Some String')
or
'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on
Converting a Unicode string
and
this
excellent, excellent, primer on character encoding.
–
–
–
–
–
–
I came here because I had funny-char-syndrome on my
requests
output. I thought
response.text
would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.
Turns out
response.encoding
was empty somehow and so
response
did not know how to properly decode the content and just treated it as ASCII (I guess).
My solution was to get the raw bytes with 'response.content' and manually apply
decode('utf_8')
to it. The result was
schöne Umlaute.
The correctly decoded
vs. the improperly decoded
All strings meant for humans should use u"".
I found that the following mindset helps a lot when dealing with Python strings:
All
Python manifest strings should use the
u""
syntax. The
""
syntax is for byte arrays, only.
Before the bashing begins, let me explain. Most Python programs start out with using
""
for strings. But then they need to support documentation off the Internet, so they start using
"".decode
and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of
""
for strings. In this case, Unicode does act like a virus and will wreak havoc.
But, if you follow my rule, you won't have this infection (because you will already be infected).
–
Thanks for contributing an answer to Stack Overflow!
-
Please be sure to
answer the question
. Provide details and share your research!
But
avoid
…
-
Asking for help, clarification, or responding to other answers.
-
Making statements based on opinion; back them up with references or personal experience.
To learn more, see our
tips on writing great answers
.