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
🌐
Python
docs.python.org › 3 › library › codecs.html
codecs — Codec registry and base classes
The following codecs provide str to bytes encoding and bytes-like object to str decoding, similar to the Unicode text encodings. Changed in version 3.8: “unicode_internal” codec is removed. The following codecs provide binary transforms: bytes-like object to bytes mappings. They are not supported by bytes.decode() (which only produces str output). ... In addition to bytes-like objects, 'base64_codec' also accepts ASCII-only instances of str for decoding
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-encode-method
Python - Strings encode() method - GeeksforGeeks
July 11, 2025 - We can encode a string by using ... characters in the input, the encoding succeeds without errors. ASCII encoding only supports characters in the range 0-127....
🌐
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.
🌐
Codecademy
codecademy.com › docs › python › strings › .encode()
Python | Strings | .encode() | Codecademy
October 23, 2023 - The second call specifies that the string will be encoded using ascii and that errors will be handled using xmlcharrefreplace. ... The following example is runnable and uses the .encode() method twice. The first call does not specify encoding or error handling, so UTF-8 and strict error handling is used. The second call specifies UTF-16 and ignore error handling is used. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
🌐
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
🌐
Honeybadger
honeybadger.io › blog › python-character-encoding
Python developer's guide to character encoding - Honeybadger Developer Blog
March 6, 2023 - However, for every ASCII character, you use an additional three bytes. Avoid character encoding errors at all cost, as they are troublesome and no developer enjoys spending time dealing with a bug. Let us look at common pitfalls in character encoding and how to fix likely errors. One common error raised when working with character encoding in Python 3 is the UnicodeEncodeError.
🌐
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")
🌐
LabEx
labex.io › tutorials › python-understand-character-encoding-in-python-585770
Character Encoding in Python | LabEx
Among these, UTF-8 is widely used due to its backward compatibility with ASCII. In Python 3, the default encoding is UTF-8, which allows for the direct use of characters from various languages, including accented characters and symbols.
🌐
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 - 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.
🌐
Python
docs.python.org › 3 › library › os.html
os — Miscellaneous operating system interfaces
In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the filesystem encoding and error handler to perform this conversion (see sys.getfilesystemencoding()).
🌐
Python
docs.python.org › 3 › builtins › functions.html
Built-in Functions — Python 3.14.7 documentation
Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent: locale.getencoding() is called to get the current locale encoding.
🌐
Unicode
unicode.org › charts
Unicode 18.0 Character Code Charts
Symbols & Punctuation | Name Index | Names Lists | Collation & Casing · Find chart by hex code: Help Conventions Terms of Use
🌐
GitHub
github.com › micropython › micropython › issues › 1631
string encode('ascii') accepts non-ASCII chars · Issue #1631 · micropython/micropython
November 19, 2015 - >>> s = b'j\xc3\xb6rg'.decode('utf-8') >>> s 'j\xf6rg' >>> s.encode('ascii') b'j\xc3\xb6rg' I would have expected an EncodingError here, like in CPyton. (BTW, why can't I input non-ASCII chars at t...
Author: micropython
🌐
SSOJet
ssojet.com › character-encoding-decoding › ascii-in-python
ASCII in Python | Encoding Standards for Programming Languages
Working with plain text often means dealing with characters that aren't standard English letters. Python's built-in capabilities for handling ASCII characters provide a robust way to process and manipulate this fundamental character encoding. This guide covers how to represent, convert, and work with ASCII values directly in Python.
🌐
UnKnoWnCheaTs
unknowncheats.me › forum › valorant › 669250-sunokis-updated-tb-28.html
[Release] Sunoki's fully updated TB - Page 28
October 28, 2024 - Page 28 - Status: Working Hello, I'm Sunoki. I've been posting bypasses and tutorials on how to update or create a triggerbot, but I noticed people just want on
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.OneHotEncoder.html
OneHotEncoder — scikit-learn 1.9.1 documentation
The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka ‘one-of-K’ or ‘dummy’) encoding scheme.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.6 documentation
Character or regex pattern to treat as the delimiter. sep=None detects the separator from the first valid row of the file with Python’s builtin sniffer tool, csv.Sniffer; it is supported only by the Python parsing engine, which will be used automatically. In addition, separators longer than 1 character and different from '\s+' will be interpreted as regular expressions and will also force the use of the Python parsing engine.
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
Image to Base64 | Base64 Encode | Base64 Converter | Base64
Sometimes you have to send or output an image within a text document (for example, HTML, CSS, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document. To prevent this, for example, you can encode image to Base64 and embed it using the data URI.