Your string is already encoded with some encoding. Before encoding it to ascii, you must decode it first.

Python is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).

You can solve the problem by explicity decoding your bytestring (using the appropriate encoding) before trying to reencode it to ascii.

Example:

s = s.decode('some_encoding').encode('ascii', 'replace')

Use the correct encoding your string was encoded in first place, instead of 'some_encoding'.

You have to know which encoding a string is using before you can decode it. Where did you get the string from?

Answer from nosklo on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_string_encode.asp
Python String encode() Method
txt = "My name is Ståle" print(txt.encode(encoding="ascii",errors="backslashreplace")) print(txt.encode(encoding="ascii",errors="ignore")) print(txt.encode(encoding="ascii",errors="namereplace")) print(txt.encode(encoding="ascii",errors="replace")) print(txt.encode(encoding="ascii",errors="xmlcharrefreplace")) Run example » ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-encode-method
Python - Strings encode() method - GeeksforGeeks
July 11, 2025 - The string "Hello, World!" is encoded into bytes using the default UTF-8 encoding. The result, b'Hello, World!', is a bytes object prefixed with b. ... The encoding format to use. The default is "utf-8". Examples include "ascii", "latin-1", ...
🌐
Vultr Docs
docs.vultr.com › python › standard library › str › encode()
Python str encode() - Encode String
December 25, 2024 - This will encode the string using ASCII. Non-ASCII characters, when encountered, will raise an error unless explicitly handled. When encoding non-ASCII characters, handling errors efficiently is essential. Python's encode() method offers multiple strategies to deal with characters that do not fall within the specified encoding.
🌐
MojoAuth
mojoauth.com › character-encoding-decoding › ascii-encoding--python
ASCII Encoding : Python | Encoding Solutions Across Programming Languages
Encoding strings in ASCII using Python is straightforward thanks to the built-in encode() method. This method transforms a string into a bytes representation, which can be essential for data storage and transmission.
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.7 documentation
A string of ASCII text is also valid UTF-8 text. UTF-8 is fairly compact; the majority of commonly used characters can be represented with one or two bytes. If bytes are corrupted or lost, it’s possible to determine the start of the next UTF-8-encoded code point and resynchronize.
🌐
Codecademy
codecademy.com › docs › python › strings › .encode()
Python | Strings | .encode() | Codecademy
October 23, 2023 - The .encode() method takes a given string and returns an encoded version of that string. If no encoding specifications are given, UTF-8 is used by default. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more! ... Learn the basics of Python 3.13, one of the most powerful, versatile, and in-demand programming languages today. ... encoding (optional): The type of encoding to use. For example, some types of encoding are UTF-32, ASCII, Base64, and UTF-16.
🌐
Programiz
programiz.com › python-programming › methods › string › encode
Python String encode()
Since Python 3.0, strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points. For efficient storage of these strings, the sequence of code points is converted into a set of bytes. The process is known as encoding. There are various encodings present which treat a string differently. The popular encodings being utf-8, ascii...
Find elsewhere
🌐
Jobtensor
jobtensor.com › Tutorial › Python › en › String-Methods-encode
Python String encode(), Definition, Syntax, Parameters, Examples | jobtensor
The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used. ... myStr = "Hello Ståle!" result = myStr.encode() print(result) # using ASCII encoding print(myStr.encode(encoding="ascii",errors="backslashreplace")) print(myStr.encode...
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › types › strings › encodings.html
Unicode and character encodings - Python Basics
Texts (str) are Unicode by default. Encoded Unicode text is represented as binary data (Bytes). Python 3 accepts many Unicode code points in identifiers. Python’s re module uses the re.UNICODE flag by default, not re.ASCII.
🌐
Real Python
realpython.com › videos › ascii-python-string-module
Working With ASCII and the Python String Module (Video) – Real Python
In this lesson, you’ll start by exploring one of the simplest character encodings, ASCII. This is a good place to start learning about character encoding because ASCII is a small and contained encoding. The built-in Python string module includes several constants that categorize ASCII text.
Published: June 30, 2020
🌐
Real Python
realpython.com › python-encodings-guide
Unicode & Character Encodings in Python: A Painless Guide – Real Python
May 20, 2019 - Here’s a handy way to represent ASCII strings as sequences of bits in Python. Each character from the ASCII string gets pseudo-encoded into 8 bits, with spaces in between the 8-bit sequences that each represent a single character:
🌐
Honeybadger
honeybadger.io › blog › python-character-encoding
Python developer's guide to character encoding - Honeybadger Developer Blog
March 6, 2023 - Each character in the ASCII table represents a single byte. However, complicated characters such as é are not ASCII-compatible in UTF-8 and are represented by two bytes encoded, xc3 and xa9, as in the first example. In the second example, strings that are not ASCII-compatible are represented by three bytes encoded.
🌐
Medium
medium.com › @dave1off › implementing-character-encodings-with-python-part-1-ascii-utf-8-e8deaa97ccdc
Implementing character encodings with Python | Part 1 — ASCII & UTF-8 | by Dave Chupreev | Medium
August 8, 2020 - String and encoding will be passed as arguments. There will be no input’s checking, that’s not the subject of this article. Encoding and decoding algorithms are presented below: ... We just iterate over sequence of the characters (encoding) or bytes(decoding) and depending on function either get integer value via ord function or retrieve a character via chr function. Why these functions are used I will discuss later. The problem with ASCII is that not all symbols can be placed in 7 bits.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-encode-decode
Python String Encode and Decode: Complete Guide | DigitalOcean
Master Python string encode() and decode() methods. Learn UTF-8, ASCII, Unicode handling, error handling modes, and practical encoding/decoding examples.
🌐
Learn By Example
learnbyexample.org › python-string-encode-method
Python String encode() Method - Learn By Example
April 20, 2020 - # Encode the string to UTF-8 S = 'Das straße' x = S.encode() print(x) # Prints b'Das stra\xc3\x9fe' Let’s try to encode the German words ‘Das straße‘, which translates to ‘The street‘ in english. ... Following example shows different error handling scheme implementations by using errors parameter. x = S.encode(encoding='ascii',errors='backslashreplace') print(x) # Prints b'Das stra\\xdfe' x = S.encode(encoding='ascii',errors='ignore') print(x) # Prints b'Das strae' x = S.encode(encoding='ascii',errors='namereplace') print(x) # Prints b'Das stra\\N{LATIN SMALL LETTER SHARP S}e' x = S.encode(encoding='ascii',errors='replace') print(x) # Prints b'Das stra?e' x = S.encode(encoding='ascii',errors='xmlcharrefreplace') print(x) # Prints b'Das straße' x = S.encode(encoding='UTF-8',errors='strict') print(x) # Prints b'Das stra\xc3\x9fe'
🌐
Python Guides
pythonguides.com › encode-function-in-python-string
Python Strings Encode() Method
August 14, 2025 - The strict mode raises an exception when it encounters characters that can’t be encoded: # Strict error handling example try: problematic_text = "User review: This product is amazing! 😊🚀" ascii_strict = problematic_text.encode('ascii', errors='strict') except UnicodeEncodeError as e: print(f"Encoding error: {e}") print("Cannot encode emoji characters to ASCII")
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › 24.3.0 › appendix › encodings.html
Unicode and character encodings - Python Basics 24.3.0
# Some strings for ctype-style character classification whitespace = " \t\n\r\v\f" ascii_lowercase = "abcdefghijklmnopqrstuvwxyz" ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ascii_letters = ascii_lowercase + ascii_uppercase digits = "0123456789" hexdigits = digits + "abcdef" + "ABCDEF" octdigits = "01234567" punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" printable = digits + ascii_letters + punctuation + whitespace · Most of these constants should be self-explanatory in their identifier names. hexdigits and octdigits refer to the hexadecimal and octal values respectively. You can use these constants for everyday string manipulation: >>> import string >>> hepy = "Hello Pythonistas!"
🌐
LabEx
labex.io › tutorials › python-how-to-encode-strings-in-python-434790
How to encode strings in Python | LabEx
In Python, understanding encoding is crucial for handling text from different languages and sources. Computers represent text using numeric codes. Different encoding standards map characters to unique numeric values: ## Default encoding demonstration text = "Hello, World!" ## Encode to bytes utf8_bytes = text.encode('utf-8') ascii_bytes = text.encode('ascii') ## Decode back to string decoded_text = utf8_bytes.decode('utf-8') graph LR A[Human Readable Text] --> B[Encoding Process] B --> C[Binary Representation] C --> D[Stored/Transmitted Data] Character set compatibility ·