w3resource

Python: Convert a byte string to a list of integers

Python Basic: Exercise-94 with Solution

Write a Python program to convert the bytes in a given string to a list of integers.

Sample Solution-1:

Python Code:

# Create a bytes object containing the bytes 'Abc'.
x = b'Abc'

# Print an empty line for clarity.
print()

# Convert the bytes of the said string to a list of integers and print the result.
print("Convert bytes of the said string to a list of integers:")
print(list(x))

# Print an empty line for clarity.
print()

Sample Output:

Convert bytes of the said string to a list of integers:
[65, 98, 99]

Sample Solution-2:

Python Code:

# Define a string named S.
S = "The quick brown fox jumps over the lazy dog."

# Print a message indicating the original string.
print("Original string:")

# Print the original string.
print(S)

# Create an empty list named nums.
nums = []

# Print a message to indicate the conversion of bytes to a list of integers.
print("\nConvert bytes of the said string to a list of integers:")

# Iterate through each character (byte) in the string S and append its ASCII value to the nums list.
for chr in S:
    nums.append(ord(chr))

# Print the list of integers.
print(nums)

Sample Output:

Original string:
The quick brown fox jumps over the lazy dog.

Convert bytes of the said string to a list of integers:
[84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103, 46]

Python Code Editor:

 

Previous: Write a Python program to get the identity of an object.
Next: Write a Python program to check if a string is numeric.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.