The ascii() method in Python returns a string containing a printable representation of an object. It escapes any non-ASCII characters in the string using x, u or U escapes.

Example

str = "Hello, World!"
print(ascii(str))
# Output: 'Hello, World!'

If the string contains non-ASCII characters, the method will escape them:

Example

str = "Héllo, World!"
print(ascii(str))
#Output: 'H\xe9llo, World!'

As you can see, the character 'é' is escaped using the x escape. This function is similar to repr() but it escapes all non-ASCII characters, whereas repr() only escapes non-printable characters.

Younes Derfoufi
my-courses.net
One thought on “Python ascii() method”

Leave a Reply