Skip to main content

Python ascii() Function

The ascii() function returns a string containing a printable version of an object. It replaces any non-ascii characters with escape characters \x, \u or \U

For example, German letter ß will be replaced with \xdf.

Syntax

ascii(object)

ascii() Parameters

Python ascii() function parameters:

ParameterConditionDescription
objectRequiredAny object (such as string, list, tuple, dictionary, etc.)

ascii() Return Value

Python ascii() function returns an equivalent printable character for a non-printable character in object.

Examples

ascii() function on String

The ascii() function on a String:

# Return a printable version by escaping non-ascii characters
my_string = 'Das straße'
result = ascii(my_string)
print(result) # Output: 'Das stra\xdfe'

output

'Das stra\xdfe'
# Return a printable version by escaping non-ascii characters
my_string = 'ñandú'
result = ascii(my_string)
print(result) # Output: '\xf1and\xfa'

output

'\xf1and\xfa'

ascii() function on List

The ascii() function on a List:

my_list = ['The street', 'Das straße']
result = ascii(my_list)
print(result) # Output: ['The street', 'Das stra\xdfe']

output

['The street', 'Das stra\xdfe']

ascii() function on Dictionary

The ascii() function on a Dictionary:

my_dict = {'EN':'The street', 'DE':'Das straße'}
result = ascii(my_dict)
print(result) # Output {'EN': 'The street', 'DE': 'Das stra\xdfe'}

output

{'EN': 'The street', 'DE': 'Das stra\xdfe'}

ascii() function on Set

The ascii() function on a Set:

set = {'Π', 'Φ', 'η'}
print(ascii(set))

output

{'\u03b7', '\u03a0', '\u03a6'}

ascii() function on Tuple

The ascii() function on a Tuple:

tuple = ('ö', '√', '¶','Ð','ß' )
print(ascii(set))

output

('\xf6', '\u221a', '\xb6', '\xd0', '\xdf')