noobprog
noobprog

Reputation: 337

How to encode a unicode string to utf-8 in python?

I am encountering this error always when getting a response from a websocket connection:

    print type(json.dumps(data))
TypeError: 'unicode' object is not callable

also:

    print type(data)
TypeError: 'unicode' object is not callable

and:

    print type(str(data))
TypeError: 'unicode' object is not callable

Can anyone teach me how to encode the data string back to utf-8?

Upvotes: 1

Views: 518

Answers (1)

Karol S
Karol S

Reputation: 9457

You (or a library you use, but more likely you) have overwritten the variable type in the global scope.

Here I'm breaking stuff in the same way:

>>> type(1)
<type 'int'>
>>> type(u'9')
<type 'unicode'>
>>> type('9')
<type 'str'>
>>> type = u'i'
>>> type(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'unicode' object is not callable

To encode Unicode string into UTF-8 bytestring, call .encode('UTF-8'):

>>> u'€'.encode('utf-8')
'\xe2\x82\xac'

Upvotes: 2

Related Questions