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..9594a1372f --- /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(f"Bytes: {raw_bytes[:100]}\n") diff --git a/python-bytes-to-strings/decode_bytes2.py b/python-bytes-to-strings/decode_bytes2.py new file mode 100644 index 0000000000..cb6e485e87 --- /dev/null +++ b/python-bytes-to-strings/decode_bytes2.py @@ -0,0 +1,12 @@ +from urllib.request import urlopen + +url = "https://example.com/" + +with urlopen(url) as response: + raw_bytes: bytes = response.read() + +print(f"Bytes: {raw_bytes[:100]}\n") + +string_format = raw_bytes[:100].decode() + +print(f"String format: {string_format}\n") diff --git a/python-bytes-to-strings/raw_bytes.py b/python-bytes-to-strings/raw_bytes.py new file mode 100644 index 0000000000..effd3cc6e9 --- /dev/null +++ b/python-bytes-to-strings/raw_bytes.py @@ -0,0 +1 @@ +raw_bytes = b"These are some interesting bytes" diff --git a/python-bytes-to-strings/replace_option_example.py b/python-bytes-to-strings/replace_option_example.py new file mode 100644 index 0000000000..a765d41247 --- /dev/null +++ b/python-bytes-to-strings/replace_option_example.py @@ -0,0 +1,2 @@ +hex_representation = b"\xff\xfe\xfa" +print(hex_representation.decode("utf-8", errors="replace")) diff --git a/python-bytes-to-strings/test.py b/python-bytes-to-strings/test.py new file mode 100644 index 0000000000..26b969af8f --- /dev/null +++ b/python-bytes-to-strings/test.py @@ -0,0 +1,4 @@ +raw_bytes = b"These are some interesting bytes" +raw_bytes.replace("y", "o") + +print(raw_bytes) diff --git a/python-bytes-to-strings/unicode_decode_error.py b/python-bytes-to-strings/unicode_decode_error.py new file mode 100644 index 0000000000..46ad504363 --- /dev/null +++ b/python-bytes-to-strings/unicode_decode_error.py @@ -0,0 +1,2 @@ +hex_representation = b"\xff\xfe\xfa" +print(hex_representation.decode("utf-8"))