diff --git a/python-bytes-to-strings/README.md b/python-bytes-to-strings/README.md new file mode 100644 index 0000000000..0a7808592d --- /dev/null +++ b/python-bytes-to-strings/README.md @@ -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/). diff --git a/python-bytes-to-strings/decode_bytes1.py b/python-bytes-to-strings/decode_bytes1.py new file mode 100644 index 0000000000..b3a66f28f0 --- /dev/null +++ b/python-bytes-to-strings/decode_bytes1.py @@ -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]) diff --git a/python-bytes-to-strings/decode_bytes2.py b/python-bytes-to-strings/decode_bytes2.py new file mode 100644 index 0000000000..09c668a647 --- /dev/null +++ b/python-bytes-to-strings/decode_bytes2.py @@ -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()) diff --git a/python-bytes-to-strings/error_handling.py b/python-bytes-to-strings/error_handling.py new file mode 100644 index 0000000000..fd776c5ee1 --- /dev/null +++ b/python-bytes-to-strings/error_handling.py @@ -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')}") diff --git a/python-bytes-to-strings/mixup.py b/python-bytes-to-strings/mixup.py new file mode 100644 index 0000000000..8ce0167e20 --- /dev/null +++ b/python-bytes-to-strings/mixup.py @@ -0,0 +1,2 @@ +raw_bytes = b"These are some interesting bytes" +raw_bytes.replace("y", "o")