Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Python 2.x Unicode strings not print as u'string'?

Tags:

python

unicode

I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. The keys and values for those dictionaries are all unicode strings, and thus they print like

{u'key1':u'value', u'key2':u'value2'}

when printed to the screen in the interactive interpreter.

Now imagine that this is a 3-level deep, 40-element dictionary. All those u characters clutter up the display, making it hard to figure out, at a glance, what the real data actually is. Even when using pprint.

Is there any way to tell the interpreter that I don't care about the difference between normal strings and unicode strings? I don't need or want the u.

The only thing I've found that might have helped was the PYTHONIOENCODING environment variable. Unfortunately, setting it to 'ascii' or 'latin-1' doesn't make those u's go away.

I'm using Python 2.6, and I use either the regular python interpreter, or iPython.

like image 748
coredumperror Avatar asked Jun 24 '11 22:06

coredumperror


People also ask

How do you print without u in Python?

In python, to remove Unicode ” u “ character from string then, we can use the replace() method to remove the Unicode ” u ” from the string. After writing the above code (python remove Unicode ” u ” from a string), Ones you will print “ string_unicode ” then the output will appear as a “ Python is easy. ”.

Why does Python print U?

The 'u' in front of a string means the string is a Unicode string. A Unicode is a way for a string to represent more characters than a regular ASCII string can. In Python 2. x, a Unicode string is marked with 'u'.

How do you change a Unicode to a string in Python?

To convert Python Unicode to string, use the unicodedata. normalize() function. The Unicode standard defines various normalization forms of a Unicode string, based on canonical equivalence and compatibility equivalence.


1 Answers

if it's json you want, just print json:

>>> import json
>>> print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4)
{
    "key2": "value2", 
    "key1": "value"
}
like image 180
SingleNegationElimination Avatar answered Sep 22 '22 08:09

SingleNegationElimination