I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
To convert ASCII to string, use the toString() method. Using this method will return the associated character.
You are probably looking for 'chr()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(chr(i) for i in L) 'hello, world'
Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(map(chr,L)) 'hello, world'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With