简体   繁体   中英

How to convert a string to a list in Python?

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!

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]

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!'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM