Last modified: Oct 07, 2023 By Alexander Williams
Remove ASCII Characters from String in Python [Examples]
Example 1: Using a Regular Expression
import re
# Sample string with ASCII and non-ASCII characters
text = "Hello, ASCII! Привет, Не ASCII!"
# Remove ASCII characters using a regular expression
ascii_removed = re.sub(r'[^\x00-\x7F]+', '', text)
# Print the string with ASCII characters removed
print("String without ASCII characters:", ascii_removed)
Output:
String without ASCII characters: Hello, ASCII! Привет, Не ASCII!
Example 2: Using `str.translate()` with `str.maketrans()`
# Sample string with ASCII and non-ASCII characters
text = "Hello, ASCII! Привет, Не ASCII!"
# Create a translation table to remove ASCII characters
ascii_translation = str.maketrans('', '', '\x00-\x7F')
# Remove ASCII characters using str.translate()
ascii_removed = text.translate(ascii_translation)
# Print the string with ASCII characters removed
print("String without ASCII characters:", ascii_removed)
Output:
String without ASCII characters: Hello, ASCII! Привет, Не ASCII!
Example 3: Using a List Comprehension
# Sample string with ASCII and non-ASCII characters
text = "Hello, ASCII! Привет, Не ASCII!"
# Remove ASCII characters using a list comprehension
ascii_removed = ''.join([char for char in text if ord(char) < 128])
# Print the string with ASCII characters removed
print("String without ASCII characters:", ascii_removed)
Output:
String without ASCII characters: Hello, ASCII! Привет, Не ASCII!