Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a character to a integer in Python, and viceversa?

I want to get, given a character, its ASCII value.

For example, for the character a, I want to get 97, and vice versa.

like image 396
Manuel Araoz Avatar asked Apr 01 '09 05:04

Manuel Araoz


People also ask

How do you turn a character into an integer in Python?

To convert Python char to int, use the ord() method. The ord() is a built-in Python function that accepts a character and returns the ASCII value of that character. The ord() method returns the number representing the Unicode code of a specified character.

How do you convert letters to numbers in Python?

We can convert letters to numbers in Python using the ord() method. The ord() method takes a single character as an input and return an integer representing the Unicode character. The string can be iterated through for loop and use an ord() method to convert each letter into number.

Can I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do you convert a character in Python?

To convert int to char in Python, use the chr() method. The chr() is a built-in Python method that returns a character (a string) from an integer (it represents the Unicode code point of the character).


2 Answers

Use chr() and ord():

>>> chr(97) 'a' >>> ord('a') 97 
like image 88
Adam Rosenfield Avatar answered Oct 07 '22 15:10

Adam Rosenfield


>>> ord('a') 97 >>> chr(97) 'a' 
like image 21
dwc Avatar answered Oct 07 '22 17:10

dwc