python - how to add unicode literal to a variable?

user1251654 picture user1251654 · Aug 9, 2012 · Viewed 19.7k times · Source

I've seen some examples like this:

for name in os.listdir(u'somedir') :

my problem is that I'm getting the somedir as a variable, so how can I append the 'u' literal?

something like

for name in ops.listdir(u+somedir)

?

Answer

Sven Marnach picture Sven Marnach · Aug 9, 2012

Given a raw byte string, you can convert it to a unicode object (Python 2.x) or a str object (Python 3.x) by decoding it:

for name in ops.listdir(somedir.decode("utf-8")):

Use whatever encoding the byte string is encoded in instead of "utf-8". If you omit the encoding, Python's standard encoding will be used (ascii in 2.x, utf-8 in 3.x).

See the Unicode HOWTO (3.x) for further information.