August 12, 2018
How to remove special characters from string except space in Python
Problem
Given an input string, provide Python code to remove all special characters except spaces.
Solution
This is a typical regular expressions question. Please find the answer below..
Code
The idea is to match only letters, spaces and exclude everything else. Take a look…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Import regular expressions module import re # Example input string string = "[~How! @are# $you% ^doing& *today\(). _I- +hope=| <everything> `is~ {fine}]" # Only keep: # Letters a-z, A-Z # Dots (.) # Numbers (\d) # Non white space (\s) # ^ means other than the provided patterns # need to be substituted by an empty string string = re.sub('[^a-zA-Z.\d\s]', '', string) # Print the final string. This should print: # How are you doing today. I hope everything is fine print(string) |
That is for today. Thanks for visiting. Questions ? Please use the comments section below.