Home > OS >  How to convert a string to a list in Python?
How to convert a string to a list in Python?

Time:01-31

so I have this Python code here:

for binary_value in binary_values:
    an_integer = int(binary_value, 2)
    ascii_character = chr(an_integer)
    ascii_string  = ascii_character
        if len(ascii_string) == 151:
            print(ascii_string)

It converts my binary code to text, the text it should convert the binary into is a string of numbers, it is text encoded in decimal. Here is the decimal (not actual decimal I'm using just for showcase purposes):

72 101 121 32 116 104 101 114 101 33

The issue is that it's a string, and I need it to be a list of integers and look something like this:

decimal=[72,101,121,32,116,104,101,114,101,33]

How would I achieve this? Thank you!

CodePudding user response:

This should do the trick:

s = '72 101 121 32 116 104 101 114 101 33'
a = list(map(int, s.split()))
print(a)

Output:

[72, 101, 121, 32, 116, 104, 101, 114, 101, 33]

CodePudding user response:

The following code snippet could help:

binary_values = [ '0b1001000', '0b1100101', '0b1111001', '0b100000', '0b1110100', '0b1101000', '0b1100101', '0b1110010', '0b1100101', '0b100001' ]
decimals = [ int(binary_value, 2) for binary_value in binary_values ]
print( decimals )
[72, 101, 121, 32, 116, 104, 101, 114, 101, 33]

Check up:

print( ''.join( [ chr(x) for x in decimals ] ) )
'Hey there!'
  •  Tags:  
  • Related