Remove Special Characters in Python

Remove all non-alphanumeric characters from a string.

BeginnerString ProgramsExample 6 of 25
remove-special-characters.py
Run in browser
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.