为什么一个新角色' u'在执行Python脚本时添加?

时间:2017-08-03 23:28:19

标签: python

我写了一个python脚本,它没有声明任何utf-8或任何东西。当我执行脚本时,我看到了角色' u'添加。这是为什么?我使用的是Python2.7版本。

access_token = token.json()['access_token']
print(' "' + access_token + '"' )
url = 'https://api.yelp.com/v3/businesses/search'
bearer = 'Bearer ' + access_token
print(bearer)
header = {'Authorization':'Bearer ' + access_token}
print(header)
params = {'location': 'San Bruno',
          'term': 'Restaurant',
          'radius':'25 miles',
          'locale':'en_US',
          'sort_by': 'rating',       
          'limit':'50'
         }

我看到一个奇怪的角色你被添加

enter image description here

2 个答案:

答案 0 :(得分:5)

所有JSON字符串都是unicode:" A string is a sequence of zero or more Unicode characters"。在Python 2.x中,一个unicode字符串的repr包括" u"在开头,因为这是unicode字符串文字的样子。

print()打印字典的str()时,字典的str调用包含项的repr。

答案 1 :(得分:2)

它只是Python 2.x中Unicode字符串的指示符。符号给出了字符串类型的可视指示符。打印容器时,引用字符串,Unicode字符串有额外的u:

>>> s = 'abc'    # byte string
>>> s            # just quotes, no u
'abc'
>>> s.decode('ascii')  # Make it a Unicode string
u'abc'
>>> u = s.decode('ascii')
>>> u
u'abc'
>>> print(u)   # both print the same way
abc
>>> print(s)
abc

容器默认使用表示法。您必须打印元素才能看到没有引号或u:

的内容
>>> L = ['abc',u'def']
>>> L
['abc', u'def']
>>> print(L)
['abc', u'def']
>>> for i in L: print i
...
abc
def