What does 'u' before a string in python mean? [duplicate]

左心房为你撑大大i 提交于 2020-07-20 17:35:03

问题


Possible Duplicate:
What does the ‘u’ symbol mean in front of string values?

I have this json text file:

{
   "EASW_KEY":" aaaaaaaaaaaaaaaaaaaaaaa",
   "EASF_SESS":" aaaaaaaaaaaaaaaaaaaaaaa",
   "PHISHKEY":" aaaaaaaaaaaaaaaaaaaaaaa",
   "XSID":" aaaaaaaaaaaaaaaaaaaaaaa"
}

If I decode it like this:

import json
data = open('data.txt').read()
data = json.loads(data)
print data['EASW_KEY']

I get this:

u' aaaaaaaaaaaaaaaaaaaaaaa' 

instead of simply:

aaaaaaaaaaaaaaaaaaaaaaa

What does this u mean?


回答1:


What does 'u' before a string in python mean?

The character prefixing a python string is called a python String Encoding declaration. You can read all about them here: https://docs.python.org/3.3/reference/lexical_analysis.html#encoding-declarations

The u stands for unicode. Alternative letters in that slot can be r'foobar' for raw string and b'foobar' for byte string.

Some help on what Python considers unicode: http://docs.python.org/howto/unicode.html

Then to explore the nature of this, run this command:

type(u'abc')

returns:

<type 'unicode'>

If you use Unicode when you should be using ascii, or ascii when you should be using unicode you are very likely going to encounter bubbleup implementationitis when users start "exploring the unicode space" at runtime.

For example, if you pass a unicode string to facebook's api.fql(...) function, which says it accepts unicode, it will happily process your request, and then later on return undefined results as if the function succeeded as it pukes all over the carpet.

As defined in this post:

FQL multiquery from python fails with unicode query

Some unicode characters are going to cause your code in production to have a seizure then puke all over the floor. So make sure you're okay and customers can tolerate that.




回答2:


The u prefix in the repr of a unicode object indicates that it's a unicode object.

You should not be seeing this if you're really just printing the unicode object itself, and not, say, a list containing it. (and, in fact, running your code doesn't actually print it like this.)



来源:https://stackoverflow.com/questions/12937172/what-does-u-before-a-string-in-python-mean

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