Decode Mixed String of Bytes + UTF-8 in Python

I have a messy CSV file where one of the city columns has half bytes and half utf-8 and includes double quotes with b’.

Example Row:  column1,"b'xc5x81xc3xb3dxc5xba, Poland'", column3

Since it is already a string, I am unable to use .decode(‘utf-8’) and it makes me encode to bytes again …which creates a double encoding. While by itself:

b'xc5x81xc3xb3dxc5xba, Poland'.decode('utf-8') 

works in Jupyter notebook to get the correct result:

'Łódź, Poland'

When trying with:

column3.encode('utf-8').decode('utf-8') 

the result is:

"b'Åx81ódź, Poland'"

How can I correctly decode this half bytes / half utf-8 string? Splitting and replacing the b’ and ” doesn’t seem to work.

You mean your column actual content is python bytes as string? Not sure why in the world you’d have something like that, but the way to decode an actual string out of it would be parsing/evaluating it first to get the bytes, and then decoding the bytes. Something like this:

import ast

wrapped_bytes = r"b'xc5x81xc3xb3dxc5xba, Poland'"
encoded_str = ast.literal_eval(wrapped_bytes)
str = encoded_str.decode()
print(str)

Edit: just in case the wrapped bytes are actually UTF8 character codes already, you can simply pull them out as, well, character codes. This said, the correct place to fix it is in whatever creates the offending csv.

wrapped_bytes = "b'xc5x81xc3xb3dxc5xba, Poland'"
just_bytes = bytes(ord(c) for c in wrapped_bytes[2:-1])
str = just_bytes.decode()
print(str)

2

Given your example row in input.csv, below will convert the 2nd column by evaluting it as a Python byte string, then decoding it as UTF-8:

import csv
import ast

with open('input.csv', newline='') as fin:
    reader = csv.reader(fin)
    for row in reader:
        row[1] = ast.literal_eval(row[1]).decode()
        print(row)

Output:

['column1', 'Łódź, Poland', ' column3']

The incorrect CSV could have been written using the csv as well, but someone encoded the city column:

import csv

with open('incorrect.csv', 'w', newline='') as fout:
    writer = csv.writer(fout)
    writer.writerow(['column1', 'Łódź, Poland'.encode(), 'column3'])

incorrect.csv:

column1,"b'xc5x81xc3xb3dxc5xba, Poland'",column3

It should not be encoded, but simply left as 'Łódź, Poland' and the file itself should be opened as UTF-8 to write it properly:

import csv

with open('correct.csv', 'w', encoding='utf8', newline='') as fout:
    writer = csv.writer(fout)
    writer.writerow(['column1', 'Łódź, Poland', 'column3'])

correct.csv (UTF-8-encoded):

column1,"Łódź, Poland",column3

As a side note, to read correct.csv from Excel, use encoding='utf-8-sig' to write the file instead. Excel assumes a localized encoding such as cp1252 unless UTF-8 w/ BOM is the encoding. This writes a signature at the beginning of the file indicating UTF-8.

All you need to do are:

  1. change doubled backslash to single one.
  2. delete the ‘b’ letter at the beginning.
  3. remove the quote mark at both head and tail.
  4. convert the string to bytes with a raw encoding and then decode it back.

I think this could help:

column3 = "b'xc5x81xc3xb3dxc5xba, Poland'"
s_string = eval(repr(column3).replace('\\', '\').replace('b', '', 1)[1:-1])
result = s_string.encode('raw_unicode_escape').decode('utf-8')
print(result)

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật