Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress the u'prefix indicating unicode' in python strings

Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?

like image 369
Ryan Avatar asked Apr 17 '09 17:04

Ryan


People also ask

How do you remove U before a string 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. ”.

How do I get rid of Unicode error in Python?

Using encode() and decode() method to remove unicode characters in Python. You can use String's encode() with encoding as ascii and error as ignore to remove unicode characters from String and use decode() method to decode() it back.

What is U prefix in Python?

The prefix 'u' in front of the quote indicates that a Unicode string is to be created. If you want to include special characters in the string, you can do so using the Python Unicode-Escape encoding.

What is the U in front of a string Python?

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'.


1 Answers

You could use Python 3.0.. The default string type is unicode, so the u'' prefix is no longer required..

In short, no. You cannot turn this off.

The u comes from the unicode.__repr__ method, which is used to display stuff in REPL:

>>> print repr(unicode('a')) u'a' >>> unicode('a') u'a' 

If I'm not mistaken, you cannot override this without recompiling Python.

The simplest way around this is to simply print the string..

>>> print unicode('a') a 

If you use the unicode() builtin to construct all your strings, you could do something like..

>>> class unicode(unicode): ...     def __repr__(self): ...             return __builtins__.unicode.__repr__(self).lstrip("u") ...  >>> unicode('a') a 

..but don't do that, it's horrible

like image 190
dbr Avatar answered Sep 23 '22 16:09

dbr