One acceptable solution is to simply build a new string by keeping only those characters that are allowed. For example, the allowed characters are:
- Letters: all Unicode alphabetic characters (using Python’s
.isalpha() method, which works for letters from any language)
- Digits: all numeric characters (using
.isdigit())
- Punctuation: the double-quote (
"), comma (,), period (.), hyphen (-), and plus sign (+)
Here is one way to do it:
def clean_text(text: str) -> str:
# Allowed punctuation characters.
allowed_chars = set('",.-+')
# Reconstruct the cleaned string by including only allowed characters.
cleaned = "".join(ch for ch in text if ch.isalpha() or ch.isdigit() or ch in allowed_chars)
return cleaned
# Example usage:
if __name__ == "__main__":
sample_text = 'Hello, world! Привет, мир! 123 + - " @#$%^&*()'
print(clean_text(sample_text))
Explanation
ch.isalpha(): This returns True for any letter from any language.
ch.isdigit(): Checks if the character is a digit.
ch in allowed_chars: Checks if the character is one of the allowed punctuation symbols.
Any symbol that does not satisfy one of these conditions is omitted from the result.
An Alternative with Regular Expressions
If you prefer a solution using regular expressions, note that Python’s built-in re module does not support Unicode properties like \p{L} out of the box. However, you can use the third‑party regex module. First, install it via:
pip install regex
Then, you can do:
import regex
def clean_text_regex(text: str) -> str:
# This regex pattern says: match any character that is not:
# - a Unicode letter (\p{L})
# - a digit (\d)
# - one of the punctuation characters: " , . - +
pattern = r"[^\p{L}\d\",\.\-\+]"
# Replace disallowed characters with an empty string.
return regex.sub(pattern, "", text)
if __name__ == "__main__":
sample_text = 'Hello, world! Привет, мир! 123 + - " @#$%^&*()'
print(clean_text_regex(sample_text))
Both solutions will remove all symbols except for letters, numbers, and the punctuation characters ", ,, ., -, and +. Choose the one that best fits your needs.