Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-bytes-to-strings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# How to Convert Bytes to Strings in Python

The materials contained in this folder are designed to complement the Real Python tutorial [How to Convert Bytes to Strings in Python](https://realpython.com/convert-python-bytes-to-strings/).
8 changes: 8 additions & 0 deletions python-bytes-to-strings/decode_bytes1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from urllib.request import urlopen

url = "https://example.com/"

with urlopen(url) as response:
raw_bytes: bytes = response.read()

print("Bytes:", raw_bytes[:100])
9 changes: 9 additions & 0 deletions python-bytes-to-strings/decode_bytes2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from urllib.request import urlopen

url = "https://example.com/"

with urlopen(url) as response:
raw_bytes: bytes = response.read()

print("Bytes:", raw_bytes[:100])
print("String:", raw_bytes[:100].decode())
6 changes: 6 additions & 0 deletions python-bytes-to-strings/error_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
encoded_text = b"d\xe9j\xe0 vu"

print(f"{encoded_text.decode("utf-8", errors="ignore") = }")
print(f"{encoded_text.decode("utf-8", errors="replace") = }")
print(f"{encoded_text.decode("utf-8", errors="backslashreplace") = }")
print(f"{encoded_text.decode('utf-8')}")
2 changes: 2 additions & 0 deletions python-bytes-to-strings/mixup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
raw_bytes = b"These are some interesting bytes"
raw_bytes.replace("y", "o")