Python ascii()

The ascii() in Python is a built-in function that returns a printable and readable version of any object such as Strings, Tuples, Lists, etc. The ascii() function will escape the non-ASCII character using \x, \u or \U escapes.

ascii() Syntax 

The syntax of the ascii() method is 

ascii(object)

ascii() Parameters

The ascii() function takes an object as an argument. The object can be of type Strings, Lists, Tuples, etc. 

ascii() Return Value

The ascii() function returns a string containing a printable representation of an object. The ascii() function will escape the non-ASCII character using \x, \u, or \U. 

For example, the non-ASCII characters “¥” will output as \xa5 and will output as \u221a

Example 1: How ascii() method works?

In case if you pass multi-line text to the ascii() function, it will replace the line breaks with “\n” as the value of the new line is “\n” 


# Normal string 
text = 'Hello World'
print(ascii(text))

# Text with Non-ASCII characters
ascii_text = 'Hëllö Wörld !!'
print(ascii(ascii_text))

# Multiline String

multiline_text =''' Hello,
Welcome to 
Python Tutorials'''

print(ascii(multiline_text))

Output

'Hello World'
'H\xebll\xf6 W\xf6rld !!'
' Hello,\nWelcome to \nPython Tutorials'

Example 2: ascii() vs print()

In the below example, we will demonstrate the difference between the ascii() function vs. the print() function. The ascii() function escapes the non-ASCII character, while the print() function does not escape the value and prints as is.


# Normal string 
text = 'Hello World'
print('ASCII version is ',ascii(text))
print('print version is ',text)

# Text with Non-ASCII characters
ascii_text = 'Hëllö Wörld !!'
print('ASCII version is ',ascii(ascii_text))
print('print version is ',ascii_text)

# Multiline String

multiline_text =''' Hello,
Welcome to 
Python Tutorials'''

print('ASCII version is ',ascii(multiline_text))
print('print version is ',multiline_text)

Output

ASCII version is  'Hello World'
print version is  Hello World
ASCII version is  'H\xebll\xf6 W\xf6rld !!'
print version is  Hëllö Wörld !!
ASCII version is  ' Hello,\nWelcome to \nPython Tutorials'
print version is   Hello,
Welcome to
Python Tutorials

0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…