Skip to content

Commit 87935df

Browse files
Lonercodeacsanybzaczynski
authored
add code for bytes to strings article (#714)
* add code for bytes to strings article * Fix indentation * Add README * Final QA --------- Co-authored-by: Philipp <[email protected]> Co-authored-by: Bartosz Zaczyński <[email protected]>
1 parent 00b3ede commit 87935df

File tree

5 files changed

+28
-0
lines changed

5 files changed

+28
-0
lines changed

python-bytes-to-strings/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Convert Bytes to Strings in Python
2+
3+
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/).
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from urllib.request import urlopen
2+
3+
url = "https://example.com/"
4+
5+
with urlopen(url) as response:
6+
raw_bytes: bytes = response.read()
7+
8+
print("Bytes:", raw_bytes[:100])
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from urllib.request import urlopen
2+
3+
url = "https://example.com/"
4+
5+
with urlopen(url) as response:
6+
raw_bytes: bytes = response.read()
7+
8+
print("Bytes:", raw_bytes[:100])
9+
print("String:", raw_bytes[:100].decode())
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
encoded_text = b"d\xe9j\xe0 vu"
2+
3+
print(f"{encoded_text.decode("utf-8", errors="ignore") = }")
4+
print(f"{encoded_text.decode("utf-8", errors="replace") = }")
5+
print(f"{encoded_text.decode("utf-8", errors="backslashreplace") = }")
6+
print(f"{encoded_text.decode('utf-8')}")

python-bytes-to-strings/mixup.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
raw_bytes = b"These are some interesting bytes"
2+
raw_bytes.replace("y", "o")

0 commit comments

Comments
 (0)