繁体   English   中英

如何在字符串前添加unicode字符? [蟒蛇]

[英]How to add unicode character before a string? [Python]

我希望能够在引用的字符串变量中添加“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)))

我相信unicode(your_string)正是你所需要的。

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

是的,format()可以工作,但有时不会。 旧版本的Python甚至没有它。 我建议:

utext = u"%s" % text

哪个会做同样的事情,如unicode.format()如果你不喜欢使用unicode()函数。 但显然,你做到了。 :d

u前缀只能用于文字。 要将现有字符串转换为unicode对象 ,请使用unicode()构造函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM