Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to ASCII value python

Tags:

python

ascii

How would you convert a string to ASCII values?

For example, "hi" would return [104 105].

I can individually do ord('h') and ord('i'), but it's going to be troublesome when there are a lot of letters.

like image 219
Neal Wang Avatar asked Dec 09 '11 23:12

Neal Wang


People also ask

How do I convert to ASCII 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 you write strings in ASCII?

Very simple. Just cast your char as an int . char character = 'a'; int ascii = (int) character; In your case, you need to get the specific Character from the String first and then cast it.

How do you find the ASCII value of a string?

ASCII value of a String is the Sum of ASCII values of all characters of a String. Step 1: Loop through all characters of a string using a FOR loop or any other loop. Step 3: Now add all the ASCII values of all characters to get the final ASCII value. A full example program is given below.


2 Answers

You can use a list comprehension:

>>> s = 'hi' >>> [ord(c) for c in s] [104, 105] 
like image 152
Mark Byers Avatar answered Oct 20 '22 07:10

Mark Byers


Here is a pretty concise way to perform the concatenation:

>>> s = "hello world" >>> ''.join(str(ord(c)) for c in s) '10410110810811132119111114108100' 

And a sort of fun alternative:

>>> '%d'*len(s) % tuple(map(ord, s)) '10410110810811132119111114108100' 
like image 25
Andrew Clark Avatar answered Oct 20 '22 06:10

Andrew Clark