2015-07-08 5 views
5

Ich möchte ein 'u' zu einer referenzierten String-Variable hinzufügen können. Ich muss dies tun, denn wenn ich in einer for-Schleife bin, kann ich nur auf die Zeichenfolge mit einem Variablennamen zugreifen.Wie Unicode-Zeichen vor einer Zeichenfolge hinzufügen? [Python]

Gibt es eine Möglichkeit, dies zu tun?

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

Antwort

8

könnten Sie entschlüsseln:

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

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

Oder die Unicode-Funktion:

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

Oder str.format:

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

Unicode-Funktion funktioniert! Vielen Dank – Tai

2

unicode(your_string) tut genau das, was Sie brauchen, glaube ich.

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

Ja, format() funktioniert, aber manchmal nicht. Ältere Versionen von Python haben es sogar nicht. Ich empfehle:

utext = u"%s" % text 

, die das gleiche tun wird, wie unicode.format() Wenn Sie Unicode() nicht wie Funktion zu verwenden. Aber offensichtlich tust du es. : D

Verwandte Themen