gpt4 book ai didi

python - 如何在字符串前添加unicode字符? [Python]

转载 作者:太空狗 更新时间:2023-10-29 22:11:00 24 4
gpt4 key购买 nike

我希望能够将“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'

最佳答案

你可以解码:

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

关于python - 如何在字符串前添加unicode字符? [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com