Remove any Non-ASCII characters in Python

This tutorial will guide you with the basics of programming in Python. One such program which is included in the basic is this one, which is deleting the occurrence of any Non-ASCII characters using Python. So let’s start learning how to remove any Non-ASCII characters in Python.

The normal range of ASCII which has been abbreviated from American Standard Code for Information Interchange is from “Zero” to “One-hundred and twenty seven”, 

ASCII codes are for representing text in computers and other devices. Most modern telecommunications equipment, character-encoding schemes are based on ASCII.
Therefore everything apart from it falls in the class of “Non-ASCII” characters, which includes emojis, Signs etc.

To Remove Non-ASCII characters:

inpstrng=input("enter the string: ")
otptstr= ""
for i in inpstrng:
    num = ord(i)
    if (num >=0) :
        if (num <= 127):
            otptstr= otptstr + i
print("The Required output is:")
print(otptstr)



Output:

enter the string: incLudes£
The Required output is:
incLudes

Variable Description(s) :

inpstrng : It is a string variable, which stores the String inputted from the user.
otptstr : It is also a string variable, But it stores the String after the process completes to give the final result; it has been initialized with “”.
i             : The variable used to travel in between all the characters.
num     : To store the ASCII value of the character

Functions Used :

input() : to take and store the input from the keyboard
print() : to print the output
ord()    : to check the particular ASCII value of that character
for        : to travel between each character of the string.

Summary :

Removal of Non-ASCII characters in a String is an easy program, in it we first take input from the user, using input function and store it in variable “inpstrng”. We then initialize “otptstr” to an empty string. After that we use a for loop to traverse between the string; while traveling we store the ASCII value of each character in “num” using the ord function and check if the ASCII value of the character is greater than or equal to “Zero” we put another if condition and check if the value is less than or equal to “One hundred and twenty-seven”.

If both the conditions give are “True”, we append the character to the “otptstr” using the sum operator and finally print it out, which gives us the desired output. In the end, we are able to remove Non-ASCII characters in Python.

Also, read:

Leave a Reply

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