Python encoding issue in script if string not hard-coded
Question: I have an encoding issue with strings I get from an external source. This
source sends the strings encoded to me and I can decode them only if they are
part of the script's code. I've looked at several threads here and even some
recommended tutorials (such as [this](https://wiki.python.org/moin/PrintFails)
one) but came up empty.

For example, if I run this:

    
    
    python -c 'print "gro\303\237e"'
    

I get:

    
    
    große
    

Which is the correct result.

But If I use it in a script, such as:

    
    
    import sys
    print sys.argv[1]
    

and call it like `test.py "gro\303\237e"`, I get:

    
    
    gro\303\237e
    

I intend to write the correct string to syslog, but I can't seem to get this
to work.

Some data on my system: \- Python 2.7.10 \- CentOS Linux \- LANG=en_US.UTF-8
\- LC_CTYPE=UTF-8

I will appreciate any help, please let me know if you need more information.
Thanks!


Answer: This will work:

    
    
    import sys
    import ast
    print ast.literal_eval('b"%s"' % sys.argv[1]).decode("utf-8")
    

But please read about
[literal_eval](https://docs.python.org/2/library/ast.html#ast.literal_eval)
first to make sure it suits your needs (I think it should be safe to use but
you should read and make sure).

