The Wayback Machine - https://web.archive.org/web/20241112011022/https://www.geeksforgeeks.org/converting-an-integer-to-ascii-characters-in-python/
Open In App

Converting an Integer to Ascii Characters in Python

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

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 converting an integer to ASCII characters in Python.

Converting An Integer To Ascii Characters In Python

Below, are the ways to Converting An Integer To Ascii Characters In Python.

An Integer To Ascii Characters Using For Loop

In this example, the below code initializes an integer, `integer_value`, to 72, then iterates through a list containing this value using a for loop, converting each element to its ASCII character representation using `chr()` and appending it to the string `ascii_char`.

Python3
integer_value = 72
ascii_char = ""

for num in [integer_value]:
    ascii_char += chr(num)

print("Using For Loop:", ascii_char)

Output
Using For Loop: H

An Integer To Ascii Characters Using chr() Function

In this example, below code assigns the ASCII character representation of the integer value 72 to the variable `ascii_char` using the `chr()` function, and then prints the result with a label. In this case, the output will be "Using chr() Function: H".

Python3
integer_value = 72
ascii_char = chr(integer_value)

print("Using chr() Function:", ascii_char)

Output
Using chr() Function: H

An Integer To Ascii Characters Using List Comprehension

In this example, below code uses list comprehension to create a list containing the ASCII character representation of the integer value 72 and then joins the characters into a string using `join()`. Finally, it prints the result with a label.

Python3
integer_value = 72
ascii_char = ''.join([chr(integer_value)])

print("Using List Comprehension:", ascii_char)

Output
Using List Comprehension: H

An Integer To Ascii Characters Using map() Function

In this example, below code applies the `chr()` function using `map()` to convert the integer value 72 to its ASCII character representation, then joins the characters into a string using `join()`. The result, 'H', is printed along with a label: "Using map() Function: H".

Python3
integer_value = 72
ascii_char = ''.join(map(chr, [integer_value]))

print("Using map() Function:", ascii_char)

Output
Using map() Function: H

Conclusion

In conclusion, converting an integer to ASCII characters in Python can be accomplished through various methods, each with its own advantages. Depending on the context and specific requirements, you can choose the method that best fits your needs. Whether you prefer the simplicity of built-in functions like chr() and map() or the explicitness of using loops, these methods provide flexibility for different scenarios in Python programming.


Previous Article
Next Article

Similar Reads

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
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
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 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
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
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Increase the ASCII value of characters of the string by the given values
Content Removed
1 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
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
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
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
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read
How to validate if input in input field has ASCII characters using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can als
4 min read
How to set ASCII Characters in MaskedTextBox in C#?
In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask that differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to insert ASCII or non-ASCII(arbitrary Unicode characters) characters in the Mas
3 min read
Count pairs of characters in a string whose ASCII value difference is K
Given string str of lower case alphabets and a non-negative integer K. The task is to find the number of pairs of characters in the given string whose ASCII value difference is exactly K. Examples: Input: str = "abcdab", K = 0 Output: 2 (a, a) and (b, b) are the only valid pairs.Input: str = "geeksforgeeks", K = 1 Output: 8 (e, f), (e, f), (f, e),
7 min read
Find the sum of the ascii values of characters which are present at prime positions
Given string str of size N, the task is to find the sum of all ASCII values of the characters that are present at prime positions. Examples: Input: str = "abcdef" Output: 298 'b', 'c' and 'e' are the only characters which are at prime positions i.e. 2, 3 and 5 respectively. And sum of their ASCII values is 298.Input: str = "geeksforgeeks" Output: 6
8 min read
Count characters in a string whose ASCII values are prime
Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime. Examples: Input: S = "geeksforgeeks" Output : 3 'g', 'e' and 'k' are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively. Input: S = "abcdefghijklmnopqrstuvwxyz" Output: 6 Approach: The idea is to gen
6 min read
Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
Given a string and a number k, the task is to find the number of substrings of length k whose sum of the ASCII value of characters is divisible by k. Examples: Input : str = "bcgabc", k = 3 Output : 2 Substring "bcg" has sum of ASCII values 300 and "abc" has sum of ASCII values 294 which are divisible by 3. Input : str = "adkf", k = 3 Output : 1 Br
8 min read
Convert all lowercase characters to uppercase whose ASCII value is co-prime with k
Given an integer 'k' and a string 'str' consisting of characters from English alphabets. The task is to convert all lower case character to uppercase whose ASCII value is co-prime with k. Examples: Input: str = "geeksforgeeks", k = 4 Output: GEEKSfOrGEEKS 'f' and 'r' are the only characters whose ASCII values aren't co-prime with 4. Input: str = "A
6 min read
Sub-strings having exactly k characters that have ASCII value greater than p
Given a string 'str', two integers 'k' and 'p'. The task is to count all the sub-strings of 'str' having exactly 'k' characters that have ASCII values greater than 'p'. Examples: Input: str = "abcd", k=2, p=98 Output: 3 Only the characters 'c' and 'd' have ASCII values greater than 98, And, the sub-strings containing them are "abcd", "bcd" and "cd"
7 min read
Average of ASCII values of characters of a given string
Given a string, the task is to find the average of ASCII values of characters in the string. Examples: Input: str = "for"Output: 109'f'= 102, 'o' = 111, 'r' = 114(102 + 111 + 114)/3 = 109 Input: str = "geeks" Output: 105 Source: Microsoft Internship Experience Approach: Start iterating through characters of the string and add their ASCII value to a
5 min read
Program to find the largest and smallest ASCII valued characters in a string
Given a string of lowercase and uppercase characters, your task is to find the largest and smallest alphabet (according to ASCII values) in the string. Note that in ASCII, all capital letters come before all small letters. Examples : Input : sample stringOutput : Largest = t, Smallest = aInput : GeeksOutput : Largest = s, Smallest = GExplanation: A
6 min read
How to remove all Non-ASCII characters from the string using JavaScript ?
In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsing ASCII values with the Array filter methodApproa
3 min read
three90RightbarBannerImg