Remove Special Characters in Python

Remove all non-alphanumeric characters from a string.

BeginnerString ProgramsExample 6 of 25
remove-special-characters.py
1# Program to remove special characters from a string
2
3s = input("Enter a string: ")
4
5cleaned = "".join(ch for ch in s if ch.isalnum() or ch.isspace())
6
7print("Cleaned string:", cleaned)

Output

Enter a string: hello@world! 123#
Cleaned string: helloworld 123

What's going on

We keep only alphanumeric characters and spaces, filtering out punctuation and symbols.

After this program

If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.