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 !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial