How to convert character to ascii in python?

Member

by evans , in category: Python , 2 years ago

How to convert character to ascii in python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by orpha , 2 years ago

@evans  You can use the .ord() method to convert a character to ascii:

1
2
3
4
5
char = "T"

print(ord(char))

# Output: 84

Member

by schuyler , a year ago

@evans 

You can use the ord() function to convert a character to its ASCII value in Python. For example:

1
2
3
char = 'a'
ascii_val = ord(char)
print(ascii_val)  # Output: 97


You can also convert a string to a list of ASCII values using a list comprehension like this:

1
2
3
string = "hello"
ascii_list = [ord(c) for c in string]
print(ascii_list)  # Output: [104, 101, 108, 108, 111]