It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
Answer from Zero Piraeus on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.6 documentation
In addition, one can create a string using the decode() method of bytes. This method takes an encoding argument, such as UTF-8, and optionally an errors argument.
Discussions

python - Python3: Decode UTF-8 bytes converted as string - Stack Overflow
Suppose I have something like: a = "Gżegżółka" a = bytes(a, 'utf-8') a = str(a) which returns string in form: b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka' Now it's send as simple string (I get it as More on stackoverflow.com
🌐 stackoverflow.com
utf 8 - Decoding utf-8 String using python 3.6 - Stack Overflow
I tried to decode the utf-8 string which I encoded successfully but can't figure out how to decode it... Actually it's decoded very well, but I just want to concatenate it with like: b = base64. More on stackoverflow.com
🌐 stackoverflow.com
UTF-8 decoding
The error is telling you the bytes you read with the f.read(name_len) was not a utf-8 encoded string. Probably you should check what the contents of the file f is, and possibly print out name_len and f.read(name_len) to check what you read is what you thought it should be. More on reddit.com
🌐 r/learnpython
7
3
June 24, 2024
Help with utf-8 encode / decode
utf-8 can handle french, is not that. >>> test = "Après un été marqué par une chute de popularité" >>> type(test) >>> btest = test.encode('utf-8') >>> type(btest) >>> print(btest) b'Apr\xc3\xa8s un \xc3\xa9t\xc3\xa9 marqu\xc3\xa9 par une chute de popularit\xc3\xa9' >>> rtest = btest.decode('utf-8') >>> print(rtest) Après un été marqué par une chute de popularité Maybe subjects are compressed, or in another place and you are picking up a different thing. More on reddit.com
🌐 r/learnpython
8
2
August 29, 2017
🌐
Mimo
mimo.org › glossary › python › string-decode
Python string decode(): Syntax, Usage, and Examples
Start your coding journey with Python. Learn basics, data types, control flow, and more ... message = b'Hello, world!' decoded_message = message.decode('utf-8') print(decoded_message) # Output: Hello, world!
🌐
Real Python
realpython.com › python-encodings-guide
Unicode & Character Encodings in Python: A Painless Guide – Real Python
May 29, 2024 - Note: If you type help(str.encode), you’ll probably see a default of encoding='utf-8'. Be careful about excluding this and just using "résumé".encode(), because the default may be different in Windows prior to Python 3.6.
🌐
Python Forum
python-forum.io › thread-10756.html
how to decode UTF-8 in python 3
June 5, 2018 - Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Str.decode(encoding = 'UTF-8',errors = 'strict') Traceback (most
Top answer
1 of 2
7

If you want to encode and decode text, that's what the encode and decode methods are for:

>>> a = "Gżegżółka"
>>> b = a.encode('utf-8')
>>> b
b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'
>>> c = b.decode('utf-8')
>>> c
'Gżegżółka'

Also, notice that UTF-8 is already the default, so you can just do this:

>>> b = a.encode()
>>> c = b.decode()

The only reason you need to specify arguments is:

  • You need to use some other encoding instead of UTF-8,
  • You need to specify a specific error handler, like 'surrogatereplace' instead of 'strict', or
  • Your code has to run in Python 3.0-3.1 (which almost nobody used).

However, if you really want to, you can do what you were already doing; you just need to explicitly specify the encoding in the str call, just as you did in the bytes call:

>>> a = "Gżegżółka"
>>> b = bytes(a, 'utf-8')
>>> b
b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'
>>> c = str(b, 'utf-8')
>>> c

Calling str on a bytes object without an encoding, as you were doing, doesn't decode it, and doesn't raise an exception like calling bytes on a str without an encoding, because the main job of str is to give you a string representation of the object—and the best string representation of a bytes object is that b'…'.

2 of 2
0

I found it. The simplest way to convert string representation of bytes to bytes again is through the eval statement:

a = "Gżegżółka"
a = bytes(a, 'utf-8')
a = str(a) #this is the input we deal with

a = eval(a) #that's how we transform a into bytes
a = str(a, 'utf-8') #...and now we convert it into string

print(a)
🌐
Delft Stack
delftstack.com › home › howto › python › decode utf 8 python
How to Decode UTF-8 in Python | Delft Stack
February 12, 2024 - Next, we use the decode method to convert this byte data into a human-readable string. We specify the encoding parameter as 'utf-8', which instructs Python to decode the bytes using the UTF-8 encoding standard.
Find elsewhere
🌐
Python Central
pythoncentral.io › encoding-and-decoding-strings-in-python-3-x
Encoding and Decoding Strings (in Python 3.x) | Python Central
December 29, 2021 - For example, if we try to use UTF-8 to decode a UTF-16-encoded version of nonlat above: [python] # We can use the method directly on the bytes >>> b'\xff\xfeW['.decode('utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte [/python]
🌐
SSOJet
ssojet.com › character-encoding-decoding › utf-8-in-python
UTF-8 in Python | Encoding Standards for Programming Languages
Use the .encode() method on a string to transform it into a bytes object, specifying the desired encoding. Conversely, the .decode() method on a bytes object converts it back into a Unicode string, again requiring the correct encoding.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-decode-method
Python Strings decode() method - GeeksforGeeks
May 11, 2026 - Encoding converts a string into bytes and decode() brings it back to its original form. ... t = "Hello, Python!" e_t = t.encode('utf-8') print("Encoded:", e_t) d_t = e_t.decode('utf-8') print("Decoded:", d_t)
🌐
Medium
lynn-kwong.medium.com › understand-the-encoding-decoding-of-python-strings-unicode-utf-8-f6f97a909ee0
Understand the encoding/decoding of Python strings (Unicode/UTF-8) | by Lynn G. Kwong | Medium
August 25, 2023 - We will introduce the basic concepts and usages of encoding and decoding in Python and how to generate unique hashes of strings with encoding and decoding.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-encode-decode
Python String Encode and Decode: Complete Guide | DigitalOcean
August 3, 2022 - Some other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’. Let’s look at a simple example of python string encode() decode() functions. str_original = 'Hello' bytes_encoded = str_original.encode(encoding='utf-8') print(type(bytes_encoded)) str_decoded = bytes_encoded.decode() print(type(str_decoded)) print('Encoded bytes =', bytes_encoded) print('Decoded String =', str_decoded) print('str_original equals str_decoded =', str_original == str_decoded)
🌐
Honeybadger
honeybadger.io › blog › python-character-encoding
Python developer's guide to character encoding - Honeybadger Developer Blog
March 6, 2023 - When we pass a binary format along with the decode method, the output is our original string. Remember, you do not have to specify UTF-8 when working with Python 3.
🌐
Reddit
reddit.com › r/learnpython › utf-8 decoding
r/learnpython on Reddit: UTF-8 decoding
June 24, 2024 -

Hi! So I'm trying to decode some utf-8 strings in Python. However some bring up an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 3: invalid start byte or something along the lines of that. Here's the function: def b_numstring(f):

name_len = int.from_bytes(f.read(4), byteorder='big')

string = f.read(name_len).decode('utf-8')

return string Any help would be appreciated. Thanks!

🌐
MojoAuth
mojoauth.com › character-encoding-decoding › utf-8-encoding--python
UTF-8 Encoding : Python | Encoding Solutions Across Programming Languages
When encoded, the UTF-8 representation is a bytes sequence that can be stored or transmitted efficiently. Decoding is the reverse process of encoding, and it is equally easy in Python. The decode() method converts a bytes object back into a string.
🌐
Reddit
reddit.com › r/learnpython › help with utf-8 encode / decode
r/learnpython on Reddit: Help with utf-8 encode / decode
August 29, 2017 -

Fun project but HELP!

I'm trying to build a small tool that logs into a Gmail account and pulls out all the emails from any specified folder (label) and places relevant data into a data frame for analysis.

All this is working splendidly except for emails that have subjects that are non-'utf-8' (e.g. french accents, etc.). This sucks as I have a lot of french in the email subjects and it kills my code.

I've been through endless documentation on encoding, decoding, unicode, etc. but nothing I do seems to work.

For example the subject:

"Après un été marqué par une chute de popularité"

gets interpreted as:

=?UTF-8?B?QXByw6hzIHVuIMOpdMOpIG1hcnF1w6kgcGFyIHVuZSBjaHV0ZSBkZSBwb3B1bGFyaXTDqQ==?=

Ay subject without extended characters renders just fine. I've been tearing my hair out for 24 hours on this one, encoding, decoding, throwing modules at the problem. I can't believe it's actually this challenging. This must be the most normal thing! What am I missing?

Subject = "Après un été marqué par une chute de popularité"

Here's the main issue:

raw_email_str = data[0][1].decode('utf-8')
email_message = email.message_from_string(raw_email_str)
msg_subj = email_message['Subject']
print (msg_subj)

Output:

=?UTF-8?B?QXByw6hzIHVuIMOpdMOpIG1hcnF1w6kgcGFyIHVuZSBjaHV0ZSBkZSBwb3B1bGFyaXTDqQ==?=
Top answer
1 of 2
2
utf-8 can handle french, is not that. >>> test = "Après un été marqué par une chute de popularité" >>> type(test) >>> btest = test.encode('utf-8') >>> type(btest) >>> print(btest) b'Apr\xc3\xa8s un \xc3\xa9t\xc3\xa9 marqu\xc3\xa9 par une chute de popularit\xc3\xa9' >>> rtest = btest.decode('utf-8') >>> print(rtest) Après un été marqué par une chute de popularité Maybe subjects are compressed, or in another place and you are picking up a different thing.
2 of 2
2
non-'utf-8' (e.g. french accents, etc.). I don't know if you grasp the essence of UTF-8: it's a way to encode all of Unicode into bytestrings that are a minimal of 8 bits per character, possibly more. This includes Tibetan scripts, Zulu, Emoji's, Klingon, whatever and also those accents. There is no such thing as a character being 'non-UTF8', it could be that you can find bytes that use another encoding, like ASCII (that doesn't feature accents) or Latin-1 (that does). Looking at your encoded string it is clear that it actually indicates being UTF-8, not something else. The encoding used is RFC 2047, the standard for e-mail header encoding, and can easily be decoded by the header sublibrary of the email library that you are already using: >>> from email.header import decode_header # decode_header will always return a list with one or more results, so select the first with [0] >>> result = decode_header('=?UTF-8?B?QXByw6hzIHVuIMOpdMOpIG1hcnF1w6kgcGFyIHVuZSBjaHV0ZSBkZSBwb3B1bGFyaXTDqQ==?=')[0] # which will contain a tuple of the encoded text and its encoding label >>> result (b'Apr\xc3\xa8s un \xc3\xa9t\xc3\xa9 marqu\xc3\xa9 par une chute de popularit\xc3\xa9', 'utf-8') # unpack for ease >>> txt, encoding = result # then decode >>> txt.decode(encoding) 'Après un été marqué par une chute de popularité' For more info read the docs here . There's also an extensive Example page for the general email library here .
🌐
Towards Data Science
towardsdatascience.com › a-guide-to-unicode-utf-8-and-strings-in-python-757a232db95c
A Guide to Unicode, UTF-8 and Strings in Python | by Sanket Gupta | Towards Data Science
September 24, 2024 - So if an incoming file is Cyrillic characters, Python 2 might fail because ASCII will not be able to handle those Cyrillic Characters. In this case, we need to remember to use decode("utf-8") during reading of files. This is inconvenient. 2. Python 3 came and fixed this.
🌐
LabEx
labex.io › tutorials › python-how-to-use-python-utf8-encoding-451217
How to use Python UTF8 encoding | LabEx
Python 3 natively supports UTF-8 encoding, making it easy to work with international text. ## UTF-8 string example text = "Hello, 世界! こんにちは!" print(text.encode('utf-8')) ... LabEx recommends understanding UTF-8 as a fundamental skill for modern Python programming. Encoding and decoding are fundamental processes for converting text between different representations in Python.
🌐
Reddit
reddit.com › r/learnpython › trouble decoding from utf-8
r/learnpython on Reddit: Trouble Decoding from UTF-8
February 11, 2025 -

I have some code that ends up retrieving a bunch of strings, and each one is basically a utf-8 encoded symbol in string format, such as 'm\xc3\xbasica mexicana'. I want to encode this into bytes and then decode it as UTF-8 so that I can convert it into something like "música mexicana". I can achieve this if I start with a string that I create myself like below:

encoded_str = 'm\xc3\xbasica mexicana'
utf8_encoded = encoded_str.encode('raw_unicode_escape')
decoded_str = utf8_encoded.decode(encoding='UTF-8')
print(decoded_str)

# This prints "música mexicana", which is the desired result

But in my actual code where I read the string from a source and don't create it myself the encoding always adds an extra backslash in front of the original string backslashes. Then when I decode it it just converts back to the original string without the second backslash.

# Exclude Artist pages
excluded_words = ['image', 'followers', 'googleapis']
excluded_words_found = any(word in hashtag for word in excluded_words)
if not excluded_words_found or len(hashtag) < 50:
    # Encode string into bytes then utf decode it to convert characters with accents    

    hashtag = hashtag.encode('raw_unicode_escape')
    hashtag = hashtag.decode(encoding='UTF-8')
   
    # Add hashtag and uri to list
    hashtags_uris.append((hashtag, uri))

I've tried so many things, including using latin1 encoding instead of raw_unicode_escape and get the same result every time. Can anyone help me make sense of this?