2013-07-01 22 views
1

想知道在我的代碼的每一行之前,'u'的意義是什麼,以及我將如何移除它們?我在Python中工作。爲什麼我的每一行輸出前都有'u'?

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': ''}, 
+2

ü==統一... – duffymo

+0

猜你調用'json.dumps',看在這個問題:http://stackoverflow.com/questions/16261174/json-output-s-just- print-the-output-withou-u?rq = 1 – maksimov

回答

5

u用於創建Unicode字符串:

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

您可以轉換使用Unicode字符串:

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

然而,這僅僅是可能的,如果在你的unicode字符串中的字符可以用ASCII表示:

>>> 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) 

你可以閱讀更多關於Python的Unicode字符串在http://docs.python.org/2/howto/unicode.html

5

u意味着它是一個Unicode字符串,如果字符串只包含ASCII chacacters那麼就沒有必要轉換到正常str爲:

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

但是你不能比較Unicode字符串用包含非ASCII字符的字節字符串:

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

僅當您將字節字符串轉換爲unicode(具有適當的enc oding):

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

文檔:Unicode HOWTO

奈德巴徹爾德的PPT:Pragmatic Unicode : How Do I Stop the Pain?

+0

@downvoter謹慎地解釋你的downvote,以便我可以改進我的答案。 –

+2

沒有讓你失望,但是「不會以任何方式影響你的輸出」是一種拉伸,你不覺得嗎? – rantanplan

+0

@rantanplan你能舉個例子說我的句子可能是錯的嗎? –

4

在字符串的前面的小寫u意味着它是一個Unicode字符串。 這只是編碼,因此根本沒有任何傷害。 Unicode字符串能夠代表更廣泛的字符(如£)比普通字符串和u不會在print s內所示:

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

您可以瞭解更多有關unicode字符串蟒蛇文件:http://docs.python.org/3/howto/unicode.html

+1

「這只是編碼,因此根本沒有傷害」。你是認真的人嗎?這裏的「只是編碼」模因是什麼?編碼是大多數怪異問題的根源。不要淡化它。每個人都應該研究bytestings和unicode之間的區別。 – rantanplan

2

要刪除unicode,使用類型轉換。

>>> x = u'abcd' 
    >>> type(x) 
    <type 'unicode'> 
    >>> y = str(x) 
    >>> type(y) 
    <type 'str'> 
相關問題