96.2k views
1 vote
How to remove all symbols from string python

User AmitE
by
7.8k points

1 Answer

5 votes

Final answer:

To remove all symbols from a string in Python, you can use regular expressions and the 're' module. First, import the 're' module. Then, use the 're.sub()' function to substitute all non-alphanumeric characters with an empty string.

Step-by-step explanation:

To remove all symbols from a string in Python, you can use regular expressions and the 're' module. First, import the 're' module. Then, use the 're.sub()' function to substitute all non-alphanumeric characters with an empty string. Here's an example:

import re

string = "Hello! How are you?"

clean_string = re.sub('[^A-Za-z0-9]+', '', string)

print(clean_string)

This will output:

HelloHowareyou

By using the regular expression '[^A-Za-z0-9]+', we match and replace any character that is not a letter or a number.

User Shafaat
by
8.0k points