Python dictionary key/value with prefixes - what's the prefix for?

折月煮酒 提交于 2019-12-24 00:13:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!