为什么在输出的每一行之前都有'u'?

时间:2013-07-01 14:10:53

标签: python json

只是想知道我的代码的每一行之前'u'的重要性是什么以及我如何能够删除它们?我在python工作。

Last login: Mon Jul  1 09:58:27 on ttys000
Samuel-Finegolds-MacBook-Pro:~ samuelfinegold$ /var/folders/jv/9_sy0bn10mbdft1bk9t14qz40000gn/T/Cleanup\ At\ Startup/tutor-394379967.500.py.command ; exit;
{u'company': {u'address': {u'city': u'Chicago',
                           u'contactname': '',
                           u'geo': {u'latitude': u'41.92113',
                                    u'longitude': u'-87.70085'},
                           u'state': u'IL',
                           u'street_address': '',
                           u'zip': u'60647'},
              u'companyname': u'Wyzant',
              u'costtype': '',
              u'description': u'WyzAnt is the leading tutoring marketplace on the web with 67,000+ tutors offering private lessons in hundreds of subjects like math, science, test prep, foreign languages, music, computers and much more.',
              u'email': '',
              u'facebook': u'https://www.facebook.com/WyzAnt',
              u'image': '',
              u'language': '',
              u'linkedin': '',
              u'logo': '',
              u'phone': u'8779992681',
              u'program': {u'costrange': u'[]',
                           u'costtype': '',
                           u'programtype': ''},

4 个答案:

答案 0 :(得分:6)

u用于创建unicode字符串:

>>> unicode_string = u'my unicode string'
>>> type(unicode_string)
<type 'unicode'>
>>> ascii_string = 'my ascii string'
>>> type(ascii_string)
<type 'str'>

您可以使用str转换unicode字符串:

>>> converted_string = str(unicode_string)
>>> type(converted_string)

但是,只有在使用ascii表示unicode字符串中的字符时才可以这样做:

>>> unicode_string = u'ö'
>>> converted_string = str(unicode_string)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0: ordinal not in range(128)

您可以在http://docs.python.org/2/howto/unicode.html

上阅读有关Python的unicode字符串的更多信息

答案 1 :(得分:5)

u表示它是一个unicode字符串,如果字符串只包含ASCII字符,那么就不需要转换为普通str

>>> "foo" == u"foo"
True

但是你无法将unicode字符串与包含非ASCII字符的字节字符串进行比较:

>>> u'ö' == 'ö'
False
>>> 'ö'       #contains bytes
'\xc3\xb6'
>>> u'ö'      #contains sequence of code-points 
u'\xf6'

只有将字节字符串转换为unicode(使用正确的编码)时才能进行比较:

>>> u'ö' == 'ö'.decode('utf-8')
True

文档:Unicode HOWTO

Ned Batchelder的ppt:Pragmatic Unicode : How Do I Stop the Pain?

答案 2 :(得分:4)

字符串前面的小写u表示它是一个unicode字符串。 它只是编码,因此完全没有害处。 Unicode字符串能够表示比普通字符串更多种类的字符(例如£),并且u不会显示在print中:

>>> print(u'hi')
'hi'

您可以从python文档中了解有关unicode字符串的更多信息:http://docs.python.org/3/howto/unicode.html

答案 3 :(得分:2)

要删除unicode,请使用类型转换。

    >>> x = u'abcd'
    >>> type(x)
    <type 'unicode'>
    >>> y = str(x)
    >>> type(y)
    <type 'str'>