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.
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.
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.
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.
You can use a list comprehension:
>>> s = 'hi' >>> [ord(c) for c in s] [104, 105]
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'
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