I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input
?
Also, I would like to test Unicode strings for equality and it looks like a standard ==
does not work.
Thank you for your help !
It should work.
raw_input
returns a byte string which you must decode using the correct encoding to get yourunicode
object. For example, the following works for me under Python 2.5 / Terminal.app / OSX:As for comparing unicode strings: can you post an example where the comparison doesn't work?
In the general case, it's probably not possible to compare unicode strings. The problem is that there are several ways to compose the same characters. A simple example is accented roman characters. Although there are codepoints for basically all of the commonly used accented characters, it is also correct to compose them from unaccented base letters and a non-spacing accent. This issue is more significant in many non-roman alphabets.
I'm not really sure, which format you mean by "Unicode format", there are several. UTF-8? UTF-16? In any case you should be able to read a normal string with
raw_input
and then decode it using the stringsdecode
method:If you have a different input encoding just use "utf-16" or whatever instead of "utf-8". Also see the codecs modules docs for different kinds of encodings.
Comparing then should work just fine with
==
. If you have string literals containing special characters you should prefix them with "u" to mark them as unicode:And if you want to output these strings again, you probably want to encode them again in the desired encoding:
raw_input()
returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following:which should work correctly in most of the cases.
We need more data about not working Unicode comparisons in order to help you. However, it might be a matter of normalization. Consider the following:
a1
anda2
are equivalent but not equal:So you might want to use the
unicodedata.normalize()
method:If you give us more information, we might be able to help you more, though.