How do I remove u chars from the following dictionary?
{u'name': u'A', u'primary_key': 1}
This data is coming from Mongo Database
find() query
so that it looks like
{'name': 'A', 'primary_key': 1}
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. ”.
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.
Unicode Literals in Python Source Code Specific code points can be written using the \u escape sequence, which is followed by four hex digits giving the code point. The \U escape sequence is similar, but expects 8 hex digits, not 4.
Remove Non-ASCII Characters From Text Python Here we can use the replace() method for removing the non-ASCII characters from the string. In Python the str. replace() is an inbuilt function and this method will help the user to replace old characters with a new or empty string.
Some databases such as Sqlite3 let you define converter and adapter functions so you can retrieve text as str rather than unicode. Unfortunately, MongoDB doesn't provide this option for any of the commonly needed types such as str, decimal or datetime:
Having eliminated Mongo options, that leaves writing Python code to do the conversion after the data is retrieved. You could write a recursive function that traverses the result to convert each field.
As a quick-and-dirty alternative, here is a little hack that may be of use:
>>> import json, ast >>> r = {u'name': u'A', u'primary_key': 1} >>> ast.literal_eval(json.dumps(r)) {'name': 'A', 'primary_key': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With