In Python 2: Normal strings (Python 2.x str) don't have an encoding: they are raw data.

In Python 3: These are called "bytes" which is an accurate description, as they are simply sequences of bytes, which can be text encoded in any encoding (several are common!) or non-textual data altogether.

For representing text, you want unicode strings, not byte strings. By "unicode strings", I mean unicode instances in Python 2 and str instances in Python 3. Unicode strings are sequences of unicode codepoints represented abstractly without an encoding; this is well-suited for representing text.

Bytestrings are important because to represent data for transmission over a network or writing to a file or whatever, you cannot have an abstract representation of unicode, you need a concrete representation of bytes. Though they are often used to store and represent text, this is at least a little naughty.

This whole situation is complicated by the fact that while you should turn unicode into bytes by calling encode and turn bytes into unicode using decode, Python will try to do this automagically for you using a global encoding you can set that is by default ASCII, which is the safest choice. Never depend on this for your code and never ever change this to a more flexible encoding--explicitly decode when you get a bytestring and encode if you need to send a string somewhere external.

Answer from Mike Graham on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_string_encode.asp
Python String encode() Method
Remove List Duplicates Reverse ... Python Study Plan Python Interview Q&A Python Training ... The encode() method encodes the string, using the specified encoding....
🌐
Python
docs.python.org › 3 › library › codecs.html
codecs — Codec registry and base classes
Given a str string of up to 256 characters representing a decoding table, returns either a compact internal mapping object EncodingMap or a dictionary mapping character ordinals to byte values. Raises a TypeError on invalid input. The full details for each codec can also be looked up directly: ... Looks up the codec info in the Python ...
🌐
Honeybadger
honeybadger.io › blog › python-character-encoding
Python developer's guide to character encoding - Honeybadger Developer Blog
March 6, 2023 - Unicode is a universal character ... refer to displayed text or characters. In Python 3, every string uses the Unicode format to represent characters by default....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-encode-method
Python - Strings encode() method - GeeksforGeeks
July 11, 2025 - String encode() method in Python is used to convert a string into bytes using a specified encoding format.
Top answer
1 of 6
34

In Python 2: Normal strings (Python 2.x str) don't have an encoding: they are raw data.

In Python 3: These are called "bytes" which is an accurate description, as they are simply sequences of bytes, which can be text encoded in any encoding (several are common!) or non-textual data altogether.

For representing text, you want unicode strings, not byte strings. By "unicode strings", I mean unicode instances in Python 2 and str instances in Python 3. Unicode strings are sequences of unicode codepoints represented abstractly without an encoding; this is well-suited for representing text.

Bytestrings are important because to represent data for transmission over a network or writing to a file or whatever, you cannot have an abstract representation of unicode, you need a concrete representation of bytes. Though they are often used to store and represent text, this is at least a little naughty.

This whole situation is complicated by the fact that while you should turn unicode into bytes by calling encode and turn bytes into unicode using decode, Python will try to do this automagically for you using a global encoding you can set that is by default ASCII, which is the safest choice. Never depend on this for your code and never ever change this to a more flexible encoding--explicitly decode when you get a bytestring and encode if you need to send a string somewhere external.

2 of 6
17

Hey! I'd like to add some stuff to other answers, unfortunately I don't have enough rep yet to do that properly :-(

FWIW, Mike Graham's post is pretty good and that's probably what you should be reading first.

Here's a few comments:

  1. The need to prefix unicode literals with "u" in 2.x is pretty easily removed in recent (2.6+) 2.x Pythons. from __future__ import unicode_literals
  2. Simialrly, ASCII is only the default source encoding. Python understands a variety of coding hints including the emacs-style # -*- coding: utf-8 -*-. For more information see PEP 0263. Changing the source encoding affects how Unicode literals (regardless of their prefix or lack of prefix, as affected by point 1) are interpreted. In Py3k, the default file encoding is UTF-8.
  3. Python of course does use an encoding internally for Unicode strings (str in py3k, unicode in 2.x) because at some point in time stuff's going to have to be written to memory. Ideally, this would never be evident to the end-user. Unfortunately nothing's perfect and you can occasionally run into problems with this: specifically if you use funky squiggles outside of the Unicode Base Multilingual Plane. Since Python 2.2, we've had what's called wide builds and narrow builds; these names refer to the type used internally to store Unicode code points. Wide builds use UCS-4, which uses 4 bytes to store a Unicode code point. (This means UCS-4's code unit size is 4 bytes, or 32 bits.) Narrow builds use UCS-2. UCS-2 only has 16 bits, and therefore can not encode all Unicode code points accurately (it's like UTF-16, except without the surrogate pairs). To check, test the value of sys.maxunicode. If it's 1114111, you've got a wide build (which can correctly represent all of Unicode). If it's less, well, don't fret too much. The BMP (code points 0x0000 to 0xFFFF) covers most people's needs. For more information, see PEP 0261.
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › types › strings › encodings.html
Unicode and character encodings - Python Basics
What’s New In Python 3.0: Text Vs. Data Instead Of Unicode Vs. 8-bit · While Unicode is an abstract encoding standard, UTF-8 is a concrete encoding scheme. The Unicode standard is a mapping of characters to code points and defines several different encodings from a single character set.
Find elsewhere
🌐
Programiz
programiz.com › python-programming › methods › string › encode
Python String encode()
Using the string encode() method, you can convert unicode strings into any encodings supported by Python.
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.7 documentation
The first encoding you might think of is using 32-bit integers as the code unit, and then using the CPU’s representation of 32-bit integers. In this representation, the string “Python” might look like this:
🌐
Python
docs.python.org › 3 › builtins › stdtypes.html
Built-in Types — Python 3.14.7 documentation
Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python).
🌐
Educative
educative.io › answers › what-is-the-string-encode-method-in-python
What is the String encode() method in Python?
The encode() method encodes strings using the provided encoding scheme. The language specifies the number of encoding techniques. UTF-8 will be used if no encoding is given. The encode() method in Python returns a string that has been encoded.
🌐
Medium
medium.com › @_keshavgarg › encoding-the-right-way-python-2-x-3c605f9e459d
Encoding the right way - Python 2.x | by KESHAV GARG | Medium
June 12, 2019 - Either play with decoded strings or encoded strings but do not mix them. Everytime you do str(value), you are actually encoding it. You can pass encoding scheme as well to this function. Many libraries / packages assume values in ASCII or if not , they try to convert it into ASCII. ... When you try to encode a value returned from str function, python realizes that it can’t do an encode on a str type, so it tries to decode it first.
🌐
VR Soft Tech
vrsofttech.com › python › string-encode-method-in-python
String encode() method in Python
Python - Quiz · The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used. Syntax · string.encode(encoding,errors) Example 1 : Copy · txt="Hello World" print(txt.encode()) print(txt.encode(encoding="ascii")) print(txt.encode(en...
🌐
Zenva
gamedevacademy.org › home › python › python string encoding tutorial – complete guide
Python String Encoding Tutorial - Complete Guide - GameDev Academy
December 12, 2023 - When our game player uses the letter ‘A’, Python refers to Unicode to understand what ‘A’ means. Let’s imagine our game player wants to share their final word with their opponent. The word needs to be delivered in a format the opponent understands, isn’t it? That’s where String Encoding comes to our aid.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.6 documentation
Encoding to use for UTF when reading/writing (ex. 'utf-8'). List of Python standard encodings .
🌐
AskPython
askpython.com › python › string › python-encode-and-decode-functions
Python encode() and decode() Functions - AskPython
February 16, 2023 - ... The type of encoding to be followed is shown by the encoding parameter. There are various types of character encoding schemes, out of which the scheme UTF-8 is used in Python by default.
🌐
Medium
medium.com › @vivekmcm1 › understanding-pythons-encode-and-decode-with-real-world-examples-5d2080d66f01
Understanding Python’s encode() and decode() with Real-World Examples | by Vivek | Medium
August 30, 2025 - errors tells Python what to do if it encounters a character that can’t be encoded (strict, ignore, replace). ... text = "Hello World" byte_text = text.encode() # Default UTF-8 encoding print(byte_text) # b'Hello World' Notice the b prefix? That indicates a bytes object. ... Here, the é character is ignored because ASCII cannot represent it. ... Decoding is the reverse process: converting bytes back into a string.
Top answer
1 of 4
87

You can't decode a unicode, and you can't encode a str. Try doing it the other way around.

2 of 4
61

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-urlencode-a-querystring-in-python
How to Urlencode a Querystring in Python? - GeeksforGeeks
July 23, 2025 - import requests data = { "site": "GeeksforGeeks", "topic": "Python URL encoding", "level": "Intermediate" } encoded_data = requests.models.RequestEncodingMixin._encode_params(data) print(encoded_data) ... In this example, we are manually encoding each key-value pair using urllib.parse.quote_plus for more granular control over the URL-encoding process. This method allows customization of how each part of the query string is encoded.
🌐
Tutorialspoint
tutorialspoint.com › python › string_decode.htm
Python String decode() Method
The encoded string is: b'Hello! Welcome to Tutorialspoint.' The decoded string is: Hello! Welcome to Tutorialspoint. The python string decode() method that takes 'utf_32' as its encoding has a variable length encoding done. If the error is specified as 'replace', then it is replaced with a replacement marker.