Home » Python » What's the u prefix in a Python string?

What's the u prefix in a Python string?

Posted by: admin November 1, 2017 Leave a comment

Questions:

Like in:

u'Hello'

My guess is that it indicates “Unicode”, is it correct?

If so, since when is it available?

Answers:

You’re right, see 3.1.3. Unicode Strings.

It’s been the syntax since Python 2.0.

Questions:
Answers:

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.

Questions:
Answers:

My guess is that it indicates “Unicode”, is it correct?

Yes.

If so, since when is it available?

Python 2.x.

(In Python 3.x the strings use Unicode by default and there’s no need for the u prefix.)

Questions:
Answers:

The following should help:

http://docs.python.org/library/functions.html#unicode

http://www.amk.ca/python/howto/unicode (skip down to “Python’s Unicode Support” if you’re already familiar with Unicode principles)

Questions:
Answers:

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).

Questions:
Answers:

It’s Unicode.

Just put the variable between str(), and it will work fine.

But in case you have two lists like the following:

a = ['co32','co36']
b = [u'co32',u'co36']

If you check set(a)==set(b), it will come as False, but if you do as follows:

b = str(b)
set(a)==set(b)

Now, the result will be True.