17
Python ascii()
ItsMyCode |
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.
The syntax of the ascii()
method is
**ascii(object)**
The ascii()
function takes an object as an argument. The object can be of type Strings , Lists , Tuples , etc.
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
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'
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
The post Python ascii() appeared first on ItsMyCode.
17