如何在字符串前添加Unicode字符?[Python]

7

我希望能够给一个字符串变量添加一个'u'。我需要这样做是因为当我在for循环中时,只能通过变量名访问字符串。

有什么办法可以实现这个需求吗?

>>> word = 'blahblah'
>>> list = ['blahblah', 'boy', 'cool']
>>> import marisa_trie
>>> trie = marisa_trie.Trie(list)
>>> word in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Argument 'key' has incorrect type (expected unicode, got str)
>>> 'blahblah' in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Argument 'key' has incorrect type (expected unicode, got str)
>>> u'blahblah' in trie
True
>>> u"blahblah" in trie
True
>>> u(word) in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'u' is not defined
>>> uword in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'uword' is not defined
>>> u+word in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'u' is not defined
>>> word.u in trie
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'u'
4个回答

12

您可以解码:

lst = ['blahblah', 'boy', 'cool']

for word in lst:
    print(type(word.decode("utf-8")))

或者使用unicode函数:

unicode(word,encoding="utf-8"))

或者使用 str.format:

for word in lst:
    print(type(u"{}".format(word)))

2

unicode(your_string)可以满足你的需求。

>>> unicode("Hello world"!)
u"Hello world!"
>>> print (unicode("Hello world"!))
"Hello world!"

1

是的,format()函数可以使用,但有时也可能会出现问题。在较旧的Python版本中甚至没有此函数。 我建议:

utext = u"%s" % text

如果您不想使用unicode()函数,也可以使用相同功能的unicode.format()。但显然,您喜欢使用unicode()函数。:D


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接