Python ascii() method is language inbuilt function and returns a string containing a printable representation of an object.
ascii() escapes the non-ASCII characters in the string using
The syntax of the
ascii() method is:
The return value is a string containing the printable characters only. All non-printable characters are escaped using
\U and will use the shortest available escape sequence between all three escapes.
å will be replaced with
2. Python ascii() example
A simple python program which prints a nornal string, and then another string which contains special characters. We will also learn to use
simpleText = "Python rocks" print(ascii(simpleText)) blogName = "HowToDoInJåvå" print(ascii(blogName)) nameList = ['how', 'to', 'do', 'in', 'jåvå'] print(ascii(nameList))
'Python rocks' 'HowToDoInJ\xe5v\xe5' ['how', 'to', 'do', 'in', 'j\xe5v\xe5']
3. Difference between ascii() and ord()
Python also has
ord() function which returns a numeric ASCII value correcsponding to the given character or symbol. For example, the ASCII value of the letter ‘B’ is 66. Refer the ascii table for all supported characters.
The noticeable difference between both methods is that
ascii() method works for objects, the whole
ord() method works for any given single character.
text = "jåvå" print(ascii(text)) char = 'A' print(char) char = 'å' print(char)
'j\xe5v\xe5' A å
Happy Learning !!