你在這裏的真正問題似乎是你得到的是價值而不是價值的表示。
>>> x = u"gcc-4.3.2"
>>> x
u'gcc-4.3.2'
>>> repr(x)
"u'gcc-4.3.2'"
>>> str(x)
'gcc-4.3.2'
如果你有任何控制你從中獲得價值的地方,我會先去那裏處理。
警告:Unicode是有原因的不同,如果你有Unicode字符,你可以碰到的問題:
>>> x = u"ĝĝ"
>>> x
u'\u011d\u011d'
>>> repr(x)
"u'\\u011d\\u011d'"
>>> str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
如果你有超過你所得到的數據沒有控制,repr(x)
值是表達你可以評估:
>>> x = "u'gcc-4.3.2'"
>>> eval(x)
u'gcc-4.3.2'
然而,做注意到,EVAL是highly unsafe for a number of reasons。
如果你要處理更安全地提取unicode字符串,你可以做這樣的事情:
>>> import re
>>> x = "u'gcc-4.3.2' u'C'"
>>> re.findall("u'(.*?)'", x)
['gcc-4.3.2', 'C']
這裏我們使用正則表達式來提取u''
包裹在字符串中的任何東西。我們使用.*?
使得操作非貪婪,確保我們不會以["gcc-4.3.2' u'C"]
作爲我們的輸出。
你是如何得到那個雙引號的字符串的?聽起來你應該先解決這個問題。 – 2012-04-08 13:19:56
是的,當你想要'str(x)''時,你似乎會得到'repr(x)''。 – 2012-04-08 13:20:43