Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how to add unicode literal to a variable?

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)

?

like image 751
user1251654 Avatar asked Aug 09 '12 17:08

user1251654


People also ask

How do you enter Unicode characters in Python?

To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2. x, you also need to prefix the string literal with 'u'.

How do you Unicode a string variable in Python?

If it is a unicode string you can just do appName. encode("utf-8") . If it is a byte string then it is already encoded with some encoding. If it's already encoded as UTF-8, then it's already how you want it and you don't need to do anything.

Can Python string include Unicode?

Web content can be written in any of these languages and can also include a variety of emoji symbols. Python's string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters.

What are Unicode literals?

A Unicode literal is a sequence of ASCII characters intermixed with escaped sequence of hex digits, all enclosed in quotes and preceded by U&.


1 Answers

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.

like image 107
Sven Marnach Avatar answered Sep 27 '22 19:09

Sven Marnach