Skip to main content
 首页 » 编程设计

Python:无法将unicode转换为字符串

2025年05月04日27emanlee

我已经尝试了所有方法,但 unicode 就是没有消失。

col = "[u'$929.95']" 
unicoded_item = to_unicode(col) # [u'test'] 
 
print type(unicoded_item) # <type 'unicode'> 
if isinstance(unicoded_item, unicode): 
    unicoded_item = unicoded_item.encode('utf8') 
    print str(unicoded_item) # [u'test'] 

我原以为整个 [u' 和 '] 会消失,但它似乎没有转换。因此,当我将此字符串保存到文本文件时,该文本文件将逐字地包含所有 unicode python 字符 [u'test'] ,而不是 test/p>

请您参考如下方法:

您有一个表示列表对象的字符串。解决这个问题的最简单方法是评估字符串以获取对象:

>>> import ast 
>>> col = "[u'$929.95']" 
>>> col2 = ast.literal_eval(col) 
>>> type(col) 
<type 'str'> 
>>> type(col2) 
<type 'list'> 
>>> col2[0] 
u'$929.95' 
>>> str(col2[0]) 
'$929.95'