0

This might be a very simple problem but i am just not able to solve it.

In my python console I do :

request.request.data.get('comment')

I get {u'price': u'21', u'unit': u'30\xd730', u'name': u'test', u'comments': u'check'}

The value of comment originally is :

            "comments" : "check",
            "name" : "test",
            "price" : "21",
            "unit" : "30×30"(multiplication sign x)

How can I solve this such that I get request.request.data.get('comment') as {u'price': u'21', u'unit': u'30x30', u'name': u'test', u'comments': u'check'}?

I tried using:

request.request.data.get('comment').get('unit').encode('utf-8')

but it returns '30\xc3\x9730'

I want to convert /xd to ascii.

2
  • use str function to get string str(request.request.data.get('comment')) Commented Oct 26, 2016 at 9:17
  • {u'price': u'21', u'unit': u'30\\xd730', u'name': u'test', u'comments': u'check'} got this. Commented Oct 26, 2016 at 9:18

2 Answers 2

1

It seems to be a feature (bug?) in methods

dict.__repr__() 

and/or

dict.__str__() 

of Python 2.7.x. Really all is Ok. You can check it by

print a[u'unit']

which prints

30x30

P.S. No problems in Python 3.5.2...

See below interactive session of Python 2.7 in unicode Pycharm console:

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
>>> a=u'\xd7'
>>> a
u'\xd7'
>>> print a
×
Sign up to request clarification or add additional context in comments.

4 Comments

comment['unit'] doesn't work for my code. It gives comment['unit'] = u'30\xd730'
print function may print it as a normal string but i am using str(comment.get('unit')) kind of thing
In Python 2.7 str is just a sequence of bytes... No encoding, etc... That's why you see escape symbols. I think you will get UnicodeEncodeError in str(comment.get('unit'))
Just remove str(...), because its argument is a Unicode object with multiplication symbol \xd7 which can't be automatically converted to ASCII, and use print to show results to the users of your program. Or use Python 3.x if possible.
0

u'something' is just the python way to display unicode character string in a list or a dict or a tuple.

If you print the value to the string itself (print request.request.data.get('comment').get('unit')), you get the actual characters.

Except if your terminal does not support it (or if python thinks so). You can try to use codecs module to force a particular encoding :

sys.stdout=codecs.getwriter('utf-8')(sys.stdout)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.