Python ascii() Method

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 \x, \u or \U escapes.

1. Syntax

The syntax of the ascii() method is:


Here the object is required method argument and it can be any Python object such as String, List, Tuple, Dictionary.

The return value is a string containing the printable characters only. All non-printable characters are escaped using \x, \u or \U and will use the shortest available escape sequence between all three escapes.

For example, å will be replaced with \xe5.

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 ascii() with List object.

simpleText = "Python rocks"

blogName = "HowToDoInJåvå"

nameList = ['how', 'to', 'do', 'in', 'jåvå']

Program output.

'Python rocks'


['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å"

char = 'A'

char = 'å'

Program output.


Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.