Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a list of ascii values to a string in python?

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?

like image 784
Electrons_Ahoy Avatar asked Oct 07 '08 21:10

Electrons_Ahoy


People also ask

How do I convert ASCII to text in Python?

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.

How do I convert a list of characters to a string in Python?

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.

How do you convert ASCII to string?

To convert ASCII to string, use the toString() method. Using this method will return the associated character.


2 Answers

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' 
like image 132
Thomas Wouters Avatar answered Oct 06 '22 08:10

Thomas Wouters


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' 
like image 40
 Avatar answered Oct 06 '22 09:10