Javaexercise.com

Python ascii() Method

Python ascii() method is a built-in method. It returns string representation of an object and escape the non-ASCII characters in the string by using \x, \u or \U escapes.

Basically, It returns a readable string version of an object by replacing non-ASCII characters.


Signature

ascii(object)

Parameter Description
object (Required) This argument can be a list, string, integer etc.


Return Value

It returns string representation of an object by replacing all non-ASCII characters.



Python ascii() Method Example

Let’s first understand, how this method works and what does it return?

#ascii characters
val1 = ascii("Javaexercise")
print(val1)
#non-ascii characters
val2 = ascii("ĴÂṼÃẼẌÈŔĈÌŜÈ")
print(val2)
 Output:
 'Javaexercise'
 '\u0134\xc2\u1e7c\xc3\u1ebc\u1e8c\xc8\u0154\u0108\xcc\u015c\xc8'

As you can see, in the above example, first value is an ascii-char string and second value is non-ascii string. So, Python interpreter prints first value as it is but replaced second-one by the escape characters.


Python ascii() Method Example2

#non-ascii vowels
val1 = ascii("Ą Ę Į Ǫ Ų")
print(val1)
#musical characters
val2 = ascii("♩ ♪ ♫ ♬ ♭ ♮ ♯")
print(val2)
 Output:
 '\u0104 \u0118 \u012e \u01ea \u0172\t'
 '\u2669 \u266a \u266b \u266c \u266d \u266e \u266f'