+1 vote
in Python by (170 points)
edited by

Currently I am working on this code:

customer_telno = customer.find('div', 'customer_phone_number')

customer_telno = '' if customer_telno is None else customer_telno.contents[0]

p.customer_info = str(customer_phone + ' ' + customer_telno).strip()

When the above snippet is run I get UnicodeEncodeError :
Traceback (most recent call last):

File "foobar.py", line 792, in <module>
    p.customer_info = str(customer_phone + ' ' + customer_telno).strip()

 UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I have tried using everything possible but couldn’t find anything which works consistently. 

Can anyone solve this problem? 

2 Answers

+3 votes
by (10.9k points)
edited by

@Ankita ,This error is occurring mainly because you are converting unicode to encoded bytes using str, so to solve the problem you need to stop str and instead use .encode() to properly encode the strings.



It returns a encoded version of a string as a bytes object.

Here, an error is set to specify different error handling scheme and by default, the error is set to “strict” which means that the encoding error raises a UnicodeError, the default encoding is set to “utf-8”.

 Using .encode() in your code:

p.customer_info = u' '.join((customer_phone, customer_telno)).encode('utf-8').strip()

if you wish to know what is python visit  this Python tutorial and Python Interview questions.

0 votes
by (107k points)

This is a classic python unicode pain point! Consider the following:

a = u'bats\u00E0'

print a

 => batsà

You can use the following video tutorials to clear all your doubts:-

Welcome to Intellipaat Community. Get your technical queries answered by top developers !