2015-07-08 19 views
5

Desidero essere in grado di aggiungere una "u" a una variabile stringa referenziata. Ho bisogno di fare questo perché quando sono in un ciclo for, posso accedere alla stringa solo da un nome di variabile.Come aggiungere un carattere unicode prima di una stringa? [Python]

C'è un modo per farlo?

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

risposta

8

Si potrebbe decodificare:

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

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

Oppure utilizzare la funzione unicode:

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

O str.format:

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

La funzione Unicode funziona! Grazie – Tai

2

unicode(your_string) fa proprio quello che ti serve, credo.

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

Sì, il formato() funzionerà, ma a volte no. Anche le versioni precedenti di Python non ce l'hanno. vi consiglio:

utext = u"%s" % text 

che farà la stessa cosa, come unicode.format() Se non si desidera utilizzare la funzione unicode(). Ma ovviamente, lo sai. : D

Problemi correlati