简体   繁体   中英

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.

Use chr() and ord() :

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

ord and chr

For long string you could use this.

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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM