>>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0
\xdc\xf1\xf1')
>>> import binascii
>>> print(binascii.hexlify(x))
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1

Use binascii if you want all of it to be printed as a hex string

Answer from Lelouch Lamperouge on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pprint.html
pprint — Data pretty printer
Source code: Lib/pprint.py The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted struc...
Discussions

How to print python Byte variable? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
python - How to do pprint in a byte array type? - Stack Overflow
Well I want it looks pretty like pprint in a byte array type: ... [\n\t{\n\t\tflight_id: 1181916, \n\t\tflight_number: VJ143, \n\t\tdeparture_time: 2021-06-10 18:25:00+07:00, \n\t\tarrival_time: 2021-06-10 20:35:00+07:00\n\t}\n]" ... [ { flight_id: 1181916, flight_number: VJ143, departure_time: 2021-06-10 18:25:00+07:00, arrival_time: 2021-06-10 20:35:00+07:00 } ] I wonder it there is any existing library helping me doing this. ... If printing ... More on stackoverflow.com
🌐 stackoverflow.com
bytes but print a string!
When printing a bytes type, Python will print the actual characters for ASCII printable characters and \x escapes for non-printable characters. More on reddit.com
🌐 r/learnpython
3
2
January 15, 2022
Coming from C, how to better understand Python's byte data type?
bytes is an array of uint8's. str is an array of uint32's, but only those that are valid Unicode values. How they iterate or display by default is unrelated to the type of data they store. The python gods decided that iterating over a bytes type should return int objects, while iterating over a str object should return length 1 strings. They also decided that the default display of bytes should be to render all visible ascii characters as ascii, and the rest as escaped hex. They made these decisions presumably due to how these datatypes are usually used. For example bytes is used for low level communication a lot, which often is human readable. More on reddit.com
🌐 r/learnpython
4
2
September 3, 2022
🌐
GitHub
github.com › sindresorhus › pretty-bytes
GitHub - sindresorhus/pretty-bytes: Convert bytes to a human readable string: 1337 → 1.34 kB
Convert bytes to a human readable string: 1337 → 1.34 kB · Useful for displaying file sizes for humans. Note that it uses base-10 (e.g. kilobyte). Read about the difference between kilobyte and kibibyte. ... import prettyBytes from 'pretty-bytes'; prettyBytes(1337); //=> '1.34 kB' prettyBytes(100); //=> '100 B' // Display with units of bits prettyBytes(1337, {bits: true}); //=> '1.34 kbit' // Display file size differences prettyBytes(42, {signed: true}); //=> '+42 B' // Localized output using German locale prettyBytes(1337, {locale: 'de'}); //=> '1,34 kB' // Fixed width for alignment (useful for progress bars and tables) prettyBytes(1337, {fixedWidth: 8}); //=> ' 1.34 kB'
Starred by 1.3K users
Forked by 88 users
Languages   JavaScript 97.7% | TypeScript 2.3%
🌐
Finxter
blog.finxter.com › 5-best-ways-to-print-a-python-bytearray
5 Best Ways to Print a Python Bytearray – Be on the Right Side of Change
February 24, 2024 - This article demonstrates five ... integers, [104, 101, 108, 108, 111]. An effective way to convert a bytearray to a readable string is by using the decode() method....
🌐
Python
peps.python.org › pep-0461
PEP 461 – Adding % formatting to bytes and bytearray | peps.python.org
This PEP proposes adding % formatting operations similar to Python 2’s str type to bytes and bytearray 1 2.
🌐
PyPI
pypi.org › project › humanfriendly
humanfriendly · PyPI
>>> from humanfriendly import format_size, parse_size >>> from humanfriendly.prompts import prompt_for_input >>> user_input = prompt_for_input("Enter a readable file size: ") Enter a readable file size: 16G >>> num_bytes = parse_size(user_input) >>> print(num_bytes) 16000000000 >>> print("You entered:", format_size(num_bytes)) You entered: 16 GB >>> print("You entered:", format_size(num_bytes, binary=True)) You entered: 14.9 GiB · To get a demonstration of supported terminal text styles (based on ANSI escape sequences) you can run the following command: ... Human friendly input/output (text formatting) on the command line based on the Python package with the same name.
      » pip install humanfriendly
    
Published   Sep 17, 2021
Version   10.0
Find elsewhere
🌐
GitHub
gist.github.com › cbwar › d2dfbc19b140bd599daccbe0fe925597
Python: Human readable file size · GitHub
Python: Human readable file size. GitHub Gist: instantly share code, notes, and snippets.
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
January 20, 2025 - This goes to show the importance of choosing the right byte order when working with longer byte sequences. Note: Contrary to popular belief, the complete bit sequences produced by little-endian and big-endian orders aren’t mirror reflections of each other: ... >>> little_endian = format(3381407744, "032b") >>> big_endian = format(3181769, "032b") >>> print(little_endian, big_endian, sep="\n") 11001001100011000011000000000000 00000000001100001000110011001001 >>> little_endian == big_endian[::-1] False
🌐
Educative
educative.io › answers › what-is-the-pretty-print-module-in-python
What is the pretty-print module in Python?
The pprint module can be used to pretty-print the Python data structures in a readable format.
🌐
Stack Overflow
stackoverflow.com › questions › 67917740 › how-to-do-pprint-in-a-byte-array-type
python - How to do pprint in a byte array type? - Stack Overflow
Well I want it looks pretty like pprint in a byte array type: ... [\n\t{\n\t\tflight_id: 1181916, \n\t\tflight_number: VJ143, \n\t\tdeparture_time: 2021-06-10 18:25:00+07:00, \n\t\tarrival_time: 2021-06-10 20:35:00+07:00\n\t}\n]" ... [ { flight_id: 1181916, flight_number: VJ143, departure_time: 2021-06-10 18:25:00+07:00, arrival_time: 2021-06-10 20:35:00+07:00 } ] I wonder it there is any existing library helping me doing this. ... If printing this string is the only thing you are interested for, you can do just print(your_string) .
🌐
Reddit
reddit.com › r/learnpython › bytes but print a string!
r/learnpython on Reddit: bytes but print a string!
January 15, 2022 -

Im learning crypto ctf with python and there is something that really can't figure out on my own

i have a flag encrypted with XOR with a key. they are represented as hex. after convert it to bytes, i xor them and then use it Crypto.Util.number.long_to_bytes() to find the flag.

before the XOR operation, the bytes values is like "\xa6\xc8\xb6s<\x9b"\xde{\xc0%2f\xa3\x86}\xf5Z\xcd\xe8c^\x19\xc73\x13"

after i removed the key that was XOR with the flag, the bytes values of flag is

crypto{x0r_i5_ass0c1at1v3}

i checked the var with type() and it's a bytes not a str. How come that before that its bytes values has hex values and then only normale characters? Or maybe those arent hex?

🌐
Java2Blog
java2blog.com › home › python › print bytes as hex in python
Print bytes as hex in Python - Java2Blog
September 26, 2022 - Python 3.5 introduced the hex() function is used to return the Hexadecimal representation of a number. We can use it to directly print Bytes as Hex in Python.
🌐
Readthedocs
humanfriendly.readthedocs.io › en › latest › readme.html
humanfriendly: Human friendly input/output in Python — humanfriendly 10.0 documentation
The humanfriendly package is currently tested on Python 2.7, 3.5+ and PyPy (2.7) on Linux and macOS. While the intention is to support Windows as well, you may encounter some rough edges. ... >>> from humanfriendly import format_size, parse_size >>> from humanfriendly.prompts import prompt_for_input >>> user_input = prompt_for_input("Enter a readable file size: ") Enter a readable file size: 16G >>> num_bytes = parse_size(user_input) >>> print(num_bytes) 16000000000 >>> print("You entered:", format_size(num_bytes)) You entered: 16 GB >>> print("You entered:", format_size(num_bytes, binary=True)) You entered: 14.9 GiB
🌐
PyPI
pypi.org › project › byte-formatter
byte-formatter · PyPI
July 9, 2024 - Byte-Formatter is a Python project for formatting bytes into a human-readable format.
      » pip install byte-formatter
    
Published   Jul 10, 2024
Version   0.0.2
🌐
Programiz
programiz.com › python-programming › methods › built-in › bytes
Python bytes()
Become a certified Python programmer. Try Programiz PRO! ... The bytes() method returns an immutable bytes object initialized with the given size and data. ... # convert string to bytes byte_message = bytes(message, 'utf-8') print(byte_message) # Output: b'Python is fun'
🌐
Reddit
reddit.com › r/learnpython › coming from c, how to better understand python's byte data type?
r/learnpython on Reddit: Coming from C, how to better understand Python's byte data type?
September 3, 2022 -

I'm reading the official docs and all, tried some examples, but still feels like it's just a string.

Then I didn't understand why when I loop through a bytes object and print the current element it comes out as an integer, but when I print the whole content of the object it comes out as string like: b'whatever is in the string', and when I cast something using bytes() it returns a string formatted as hex.

Top answer
1 of 2
10
bytes is an array of uint8's. str is an array of uint32's, but only those that are valid Unicode values. How they iterate or display by default is unrelated to the type of data they store. The python gods decided that iterating over a bytes type should return int objects, while iterating over a str object should return length 1 strings. They also decided that the default display of bytes should be to render all visible ascii characters as ascii, and the rest as escaped hex. They made these decisions presumably due to how these datatypes are usually used. For example bytes is used for low level communication a lot, which often is human readable.
2 of 2
5
text = '🐘 😊' print(f'{text!r} - {len(text)=}') # '🐘 😊' - len(text)=3 data = text.encode() print(f'{data!r} - {len(data)=}') # b'\xf0\x9f\x90\x98 \xf0\x9f\x98\x8a' - len(data)=9 A str is a sequence of characters (unicode codepoint), but a bytes is a sequence of... bytes. Unsigned integers in range 0-255. One can obtain bytes by encoding a str, or by ASCII code literal (as you do), or from other methods like sockets, binary file IO, structure packing, or various others. import struct data = struct.pack('!3h', 20, 21, 22) print(f'{data!r} - {len(data)=}') # b'\x00\x14\x00\x15\x00\x16' - len(data)=6 tup = struct.unpack('!3h', b'\x00\x17\x00\x18\x00\x19') print(f'{tup!r}') # (23, 24, 25) The byte output format is to show bytes as ascii characters, or the hex if there is no ascii character for that byte. You can force hex representation with data.hex() https://docs.python.org/3/library/stdtypes.html#bytes.hex or fetch all the integer values by putting them into a list list(data)
Top answer
1 of 1
5

Just wanted to share this little snippet in case anyone finds it usefeul, this function converts byte-sizes (like the ones you'd get from os.stat(r'C:\1.pdf').st_size)

from typing import Union
def readable_size(size: Union[int, float, str]) -> str:
    units = ('KB', 'MB', 'GB', 'TB')
    size_list = [f'{int(size):,} B'] + [f'{int(size) / 1024 ** (i + 1):,.1f*} {u}' for i, u in enumerate(units)]
    return [size for size in size_list if not size.startswith('0.')][-1]

If you don't want to do from typing import Union just remove that type-hint from the function, this is here just to show that this function can accept int, float, and str arguments. A stripped down version would look like this:

def readable_size(size):
    units = ('KB', 'MB', 'GB', 'TB')
    size_list = [f'{int(size):,} B'] + [f'{int(size) / 1024 ** (i + 1):,.1f*} {u}' for i, u in enumerate(units)]
    return [size for size in size_list if not size.startswith('0.')][-1]

Examples:

>>> import random
>>> for i in range(15):
...     size = random.randint(1 ** i, 9 ** i)
...     print(f'{size} = {readable_size(size)}')
...
1 = 1 B
3 = 3 B
61 = 61 B
267 = 267 B
5127 = 5.0 KB
37700 = 36.8 KB
68512 = 66.9 KB
342383 = 334.4 KB
42580724 = 40.6 MB
40250452 = 38.4 MB
1789601996 = 1.7 GB
16242182039 = 15.1 GB
131167506597 = 122.2 GB
1827741623713 = 1.7 TB
5613973017836 = 5.1 TB

Limitations: this function only lists units up to terabytes (TB), but that can easily be modified by extending the units tuple. Obviously this uses f-strings so only applies for python versions above 3.6

🌐
GeeksforGeeks
geeksforgeeks.org › python › get-file-size-in-bytes-kb-mb-and-gb-using-python
Get File Size in Bytes, Kb, Mb, And Gb using Python - GeeksforGeeks
July 23, 2025 - In this example, the code uses Python OS Module to get the size of a file named 'example.txt'. It then converts the file size from bytes to kilobytes, megabytes, and gigabytes and prints the results with two decimal places.