What Is The Ascii() Function In Python?
Maybe your like
The ascii() function in Python is used to return a string that is the printable representation of an object. The printable representation of a string contains:
- The ASCII characterscharacters with ASCII codes from 0-127 of the string are returned as-is.
- The non-ASCII characterscharacters that cannot be represented by a 7-bit ASCII code are replaced by the escape characters. The escape characters are the hexadecimal representation of the encoded codes of the non-ASCII characters.
Syntax
The ascii() function can be declared as shown in the code snippet below.
ascii(obj)- obj: The object whose printable representation is required.
Return value
The ascii() function returns the printable representation of the object obj.
ascii() versus print()
The print() function prints the string on the output stream as it is. On the other hand, the ascii() function escapes the non-ASCII characters.
Example 1
Consider the code snippet below, which demonstrates the use of the ascii() function.
str1 = 'Hêllo wörld!' print('str1: ', str1) print('print(str1)', str1)print('ascii(str1):', ascii(str1)) RunExplanation
- We declare a string str1 in line 1.
- We use the print() function in line 3 to print str1. The print() function simply prints str1 as it is.
- We use the ascii() function in line 4 to get the printable representation of str1. The non-ASCII character ê is replaced by the escape sequence \xea, which is the hexadecimal representation of its encoded code. Similarly, the non-ASCII character ö is replaced by the escape sequence \xf6.
Example 2
Consider another example of the ascii() method, in which the code returns a printable representation of a list of strings.
lst1 = ['HËllo', 'åpple', 'çomputer'] print('lst1: ', lst1) print('ascii(lst1):', ascii(lst1))RunExplanation
We declare a list of strings lst1 in line 1. We use the ascii() method in line 3, which returns the printable representation of all the members of the list.
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Tag » Code Ascii Characters Python
-
Python Program To Find ASCII Value Of Character - Toppr
-
Python Program To Find ASCII Value Of Character - Programiz
-
How To Get The ASCII Value Of A Character - Python - Stack Overflow
-
Python Ascii() Method (With Examples) - TutorialsTeacher
-
Python Program To Find ASCII Value Of A Character
-
ASCII Value Of Letter In Python - W3resource
-
Handling ASCII Character In Python | By Uniqtech | Interview Buddy
-
ASCII Chart - Python Reference (The Right Way) - Read The Docs
-
Python Programming/Strings - Wikibooks, Open Books For An Open ...
-
Ascii() In Python - GeeksforGeeks
-
Python Ascii() Function - W3Schools
-
Unicode & Character Encodings In Python: A Painless Guide
-
Program To Print ASCII Value Of A Character - GeeksforGeeks
-
How To Check If A String Contains All ASCII Characters In Python