fix ascii codec cant encode error

How to Fix ‘ASCII codec can’t encode’ error in Python

While using python web frameworks such as Django or Flask, you may get an error saying ‘ASCII codec can’t encode’ error. In this article, we will learn how to fix this problem in Python.

How to Fix ‘ASCII codec can’t encode’ error in Python

Typically we get ‘ASCII codec can’t encode’ error in Python when we use str() function to convert string from Unicode to encoded text. Here is a sample error message.

Traceback (most recent call last):
  File "", line 792, in <module>
    var3 = str(var1 + ' ' + var2).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

This happens because we have used str() function to encode string. If there are characters that are incompatible with str() function, you will get this error. So you should use encode() function instead of str() to convert Unicode strings to other encodings.

For example, instead of using

var3 = str(var1 + ' ' + var2)

you need to use something like the following.

var3= u' '.join((var1, var2)).encode('utf-8')

Let us look at the above command in detail. We join empty Unicode string u” with var1 and var2 using join() function. We further call encode(‘utf-8’) function to encode the result to UTF8 encoding.

In this article, we have learnt how to fix ‘ASCII codec can’t encode’ error in Python. You need to use encode() function instead of using str() for encoding purposes. If you want to decode string, use decode() function instead.

This is a common problem in websites and web applications built using python or python frameworks such as Django, Flask, etc.

Also read:

How to Print Curly Braces in String in Python
How to Set Timeout on Function Call in Python
How to Set Default Value for Datetime Column in MySQL
How to Empty Array in JavaScript
How to Set Query Timeout in MySQL

Leave a Reply

Your email address will not be published.