The Wayback Machine - https://web.archive.org/web/20241006194635/https://www.geeksforgeeks.org/ascii-in-python/
Open In App

ascii() in Python

Last Updated : 08 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, we have ascii() function that returns a string containing a printable representation of an object. In this article, we will see about ascii() in Python.

Python ascii() Function

Python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes. It’s a built-in function that takes one argument and returns a string that represents the object using only ASCII characters.

Python ascii() Function Syntax

Syntax: ascii(object)

  • object: Any Python object (ex.: string, int, list, tuple, set, etc.)

Returns: Returns a string as a printable representation of the object passed, escaping the non-ASCII characters.

The method can take only one parameter, an object that can be a list, strings, etc. As already discussed, it returns a printable representation of an object.

Usage of Python ascii() Function

We see that in these examples, all the non-ASCII characters have been escaped, i.e. their encoded code gets displayed by using the ascii() method.

Python3




print(ascii("¥"))


Output

'\xa5'


We can use Python ascii() function in the following ways:

  • Using ascii() on Python String containing non-ASCII characters
  • Python ascii() on new line characters
  • Using Python ascii() on Set
  • Using Python ascii() on Tuple
  • Using Python ascii() on List

Using ascii() on Python String containing non-ASCII characters

In this example, test_str variable contains not-ASCII character and our task is to display its ASCII value from the given string.

Python3




# Python program to illustrate ascii()
test_str = "G ë ê k s f ? r G ? e k s"
print(ascii(test_str))


Output

'G \xeb \xea k s f ? r G ? e k s'


Python ascii() on new line characters

Here we take a variable with multiline string and pass it into the ascii() and it returns “\n”, the value of new line is “\n”.

Python3




test_str = '''Geeks
for
geeks'''
print(ascii(test_str))


Output

'Geeks\nfor\ngeeks'


Using Python ascii() on Set

Below example shows how to use Python ascii() on Python Set.

Python3




# Python ascii() on Set
test_set = {"Š", "E", "T"}
print("ascii on Python set:", ascii(test_set))


Output

ascii on Python set: {'\u0160', 'T', 'E'}


Python ascii() on List

In this example, we are using ascii() on Python List.

Python3




# Python ascii() on List
test_list = ["Ň", "ĕ", "Ŵ"]
print("ascii on Python list:", ascii(test_list))


Output

ascii on Python list: ['\u0147', '\u0115', '\u0174']


Using Python ascii() on Tuple

In this example, we are using Python ascii() on Python Tuple.

Python3




# Python ascii() on Tuple
test_tuple = ("Ģ", "Õ", "Õ", "D")
print("ascii on Python tuple:", ascii(test_tuple))


Output

ascii on Python tuple: ('\u0122', '\xd5', '\xd5', 'D')




Previous Article
Next Article

Similar Reads

What is ASCII - A Complete Guide to Generating ASCII Code
The American Standard Code for Information Interchange, or ASCII, is a character encoding standard that has been a foundational element in computing for decades. It plays a crucial role in representing text and control characters in digital form. Historical BackgroundASCII has a rich history, dating back to its development in the early 1960s. Origi
13 min read
Substring with maximum ASCII sum when some ASCII values are redefined
Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters. Note: Uppercase & lowercase both will be present in the string W. Input: W = "abcde", N = 1,
9 min read
Check if a string contains a non-ASCII value in Julia - ascii() Method
The ascii() is an inbuilt function in Julia which is used to convert a specified string to a String type and also check the presence of ASCII data. If the non-ASCII byte is present, throw an ArgumentError indicating the position of the first non-ASCII byte. Syntax: ascii(s::AbstractString) Parameters:s::AbstractString: Specified stringReturns: It r
1 min read
ASCII NULL, ASCII 0 ('0') and Numeric literal 0
The ASCII (American Standard Code for Information Interchange) NULL and zero are represented as 0x00 and 0x30 respectively. An ASCII NULL character serves as a sentinel character of strings in C/C++. When the programmer uses '0' in his code, it will be represented as 0x30 in hex form. What will be filled in the binary integer representation in the
3 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
Converting an Integer to Ascii Characters in Python
In Python, working with integers and characters is a common task, and there are various methods to convert an integer to ASCII characters. ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents text in computers. In this article, we will explore some simple and commonly used methods for convertin
3 min read
Python Encode Unicode and non-ASCII characters into JSON
This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understanding of how to work with Unicode and non-ASCII charac
5 min read
How To Fix - UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) in Python
Several errors can arise when an attempt to change from one datatype to another is made. The reason is the inability of some datatype to get casted/converted into others. One of the most common errors during these conversions is Unicode Encode Error which occurs when a text containing a Unicode literal is attempted to be encoded bytes. This article
2 min read
Transliterating non-ASCII characters with Python
Transliteration is a process of writing the word of one language using similarly pronounced alphabets in other languages. It deals with the pronunciation of words in other languages. Similarly, in computer language, the computer can handle ASCII characters but has problems with non-ASCII characters. There are some times when we are unable to skip n
3 min read
Generate simple ASCII tables using prettytable in Python
Prettytable is a Python library used to print ASCII tables in an attractive form and to read data from CSV, HTML, or database cursor and output data in ASCII or HTML. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border.  Installation In order to be able to use prettytable libra
5 min read
Map function and Dictionary in Python to sum ASCII values
We are given a sentence in the English language(which can also contain digits), and we need to compute and print the sum of ASCII values of the characters of each word in that sentence. Examples: Input : GeeksforGeeks, a computer science portal for geeksOutput : Sentence representation as sum of ASCII each character in a word: 1361 97 879 730 658 3
2 min read
Converting an image to ASCII image in Python
Introduction to ASCII art ASCII art is a graphic design technique that uses computers for presentation and consists of pictures pieced together from the 95 printable (from a total of 128) characters defined by the ASCII Standard from 1963 and ASCII-compliant character sets with proprietary extended characters (beyond the 128 characters of standard
9 min read
Convert Unicode to ASCII in Python
Unicode is the universal character set and a standard to support all the world's languages. It contains 140,000+ characters used by 150+ scripts along with various symbols. ASCII on the other hand is a subset of Unicode and the most compatible character set, consisting of 128 letters made of English letters, digits, and punctuation, with the remain
2 min read
Increase the ASCII value of characters of the string by the given values
Content Removed
1 min read
PLSQL | ASCII Function
The string in PL/SQL is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. The ASCII Function in PLSQL is used to return the NUMBER code that represents the specified character. Syntax ASCII( single_character ) Parameters Used: single_ch
1 min read
ASCII() Function in SQL Server
The ASCII() function returns the ASCII value of the leftmost character of a character expression. Syntax : ASCII(character_expression) Parameter : This method accepts a single-parameter as mentioned above and described below : character_expression : It can be a literal character, an expression of a string, or a column. If more than one character is
2 min read
Queries to calculate sum of squares of ASCII values of characters of a substring with updates
Given a string S of length N and a 2D array of strings Q[][] consisting of M queries of the following type: Query("U", "I", "X"): Update the character at index I with the character X.Query("S", "L", "R"): Print the sum of the squares of the position of the characters in the substring {S[L], ...., S[R]} according to the English alphabets. Examples:
15+ min read
What is the full form of ASCII?
Answer: The full form of ASCII is American Standard Code for Information Interchange.It is a widely used standard for encoding characters in computers and digital communication systems. It was created in the 1960s to make sure that text looked the same on all devices and platforms. ASCII uses a 7-bit binary code to represent 128 different character
3 min read
Program to Convert ASCII to Unicode
In this article, we will learn about different character encoding techniques which are ASCII (American Standard Code for Information Interchange) and Unicode (Universal Coded Character Set), and the conversion of ASCII to Unicode. Table of Content What is ASCII Characters?What is ASCII Table?What is Unicode?Need for ASCII to Unicode ConversionAlgor
4 min read
Program to Convert Unicode to ASCII
Given a Unicode number, the task is to convert this into an ASCII (American Standard Code for Information Interchange) number. ASCII numberASCII is a character encoding standard used in communication systems and computers. It uses 7-bit encoding to encode 128 different characters 0-127. These values generally include numbers, letters, punctuation,
4 min read
PyTest: Interactive Output instead of pure ASCII
There are numerous benefits of testing the code. It assures that modifications to the code won't result in regressions and boosts the confidence that the code acts as we anticipate. We should make the most of all the tools to make writing and maintaining tests as comfortable as we can because it is an exacting job. There are a number of different a
5 min read
Remove k characters in a String such that ASCII sum is minimum
Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2 characters from the string "ABbc" to minimize the
7 min read
Minimum cost to make the String palindrome using ASCII values
Given an input string S, the task is to make it a palindrome and calculate the minimum cost for making it a palindrome, where you are allowed to use any one of the following operations any number of times: For replacing the current character with another character the cost will be the absolute difference in ASCII (American Standard Code for Informa
5 min read
Maximize ascii sum removing K characters in String
Given a string s and an integer K, the task is to remove K characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is maximized. Examples: Input: s = "word", K = 2Output: 233Explanation: We need to remove exactly 2 characters from the string "word" to maximize the
9 min read
Find frequency of each digit 0-9 by concatenating ASCII values of given string
Given string str, the task is to find the frequency of all digits (0-9) in a string created by concatenating the ASCII values of each character of the given string str. Example: Input: str = "GeeksForGeeks"Output: 7 21 0 0 1 2 0 5 0 0Explanation: The array of ASCII values of all characters of the given string is {71, 101, 101, 107, 115, 70, 111, 11
5 min read
Program to convert given Binary to its equivalent ASCII character string
Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Examples: Input: str = "0110000101100010"Output: abExplanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'.01100010 = 98, ASCII value of 98 is 'b'.Therefore, the required
9 min read
Sort the string as per ASCII values of the characters
Given a string S of size N, the task is to sort the string based on its ASCII values. Examples: Input: S = "Geeks7"Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets. Input: S = "GeeksForGeeks"Output: FGGeeeekkorss Approach: The idea to solve this problem is to maintain an
6 min read
Sort an array of strings in increasing order of sum of ASCII values of characters
Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of the ASCII (American Standard Code for Information Interchange) value of their characters. Examples: Input: arr[] = {"for", "geeks", "app", "best"}Output: app for best geeksExplanation:Sum of ASCII values of characters of each string is: {
7 min read
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number
Given an array arr[] of size N containing strings, the task is to count the number of strings having the sum of ASCII (American Standard Code for Information Interchange) values of characters equal to an Armstrong Number number or a Prime Number. Examples: Input: arr[] = {"hello", "nace"}Output:Number of Armstrong Strings are: 1Number of Prime Stri
12 min read
How to Display Random ASCII Art on Linux Terminal?
Here we are going to see how to print the drawing on the terminal in the form of ASCII characters. ASCII-Art-Splash-Screen is a tool written in python that pulls a random drawing from a repository and shows it every time you open the terminal. This works on UNIX-based systems like Linux and macOS.  Now let's see how to install the ASCII-Art-Splash-
2 min read