Manuel Araoz
Manuel Araoz

Reputation: 16406

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.

Upvotes: 438

Views: 748070

Answers (5)

Alec
Alec

Reputation: 9536

Not OP's question, but given the title How can I convert a character to a integer in Python,

int(num) <==> ord(num) - ord('0')

str(char) <==> ord(char) - ord('a')

Upvotes: 5

Pjl
Pjl

Reputation: 1812

For long string you could use this.

 ''.join(map(str, map(ord, 'pantente')))

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400156

Use chr() and ord():

>>> chr(97)
'a'
>>> ord('a')
97

Upvotes: 742

dwc
dwc

Reputation: 24890

>>> ord('a')
97
>>> chr(97)
'a'

Upvotes: 160

rmmh
rmmh

Reputation: 7095

ord and chr

Upvotes: 22

Related Questions