问题
I've seen a Python dict looks like this lately:
test1 = {u'user':u'user1', u'user_name':u'alice'}
This confuses me a bit, what is the u
before the key/value pair for? Is it some sort of prefix? How is this different:
test2 = {'user':'user1', 'user_name':'alice'}
I've tried to play with both test1 and test2; they don't seem different at all. Can somebody explain what the prefix is for?
>>> test1 = {u'user':u'user1', u'user_name':u'alice'}
>>> test2 = {'user':'user1', 'user_name':'alice'}
>>> print test1[u'user']
user1
>>> print test1['user']
user1
>>> print test2['user']
user1
>>> print test2[u'user']
回答1:
In Python 2, you have to force Unicode character to remain in Unicode.
So, u
prevents the text to translate to ASCII. (remaining as unicode)
For example, this won't work in Python 2:
'ô SO'.upper() == 'Ô SO''
Unless you do this:
u'ô SO'.upper() == 'Ô SO'
You can read more on this: DOCS
Some history: PEP 3120
回答2:
u'unicode string'
will make the string a type unicode, where without the prefix the string is an ASCII type string 'ASCII string'
.
来源:https://stackoverflow.com/questions/16224115/python-dictionary-key-value-with-prefixes-whats-the-prefix-for