How to Remove Special Characters Except for Space from a String in Python [9 Ways]

In this Python tutorial, we will explore 9 different methods to “remove special characters except for space from a string in Python” with practical and realistic examples for your better understanding.

Removing special characters from the string is the concept of data cleaning in Python. I got one task where I needed to remove all special characters from the text file. So, I got 9 different techniques that helped me to clean the unwanted data.

These are the 9 different approaches to remove special characters except for space from a string in Python.

  1. using re.sub()
  2. using str.isalnum()
  3. re.split()
  4. using replace()
  5. Using join with generator
  6. Using findall()
  7. Using translate()
  8. Using filter()
  9. Using Map and lambda function

Let’s see them all one by one using some illustrative examples.

Remove special characters except for space from a string in Python using re.sub() function

The sub() function from the re module in Python allows us to replace occurrences of a pattern in a string with another string.

We can leverage this to remove special characters except for spaces by replacing them with an empty string.

Let’s see the practical example to remove special characters except for space from a string in Python

Code:

import re

def remove_special_characters(text):
    return re.sub(r'[^a-zA-Z0-9\s]', '', text)

text = "Welcome! To the USA."
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Welcome To the USA

Attached is a screenshot of my Python code executed in Visual Studio.

remove special characters except for space from a string in Python

Remove special characters except space from string in Python using str.isalnum()

The str.isalnum() method in Python checks if all string characters are alphanumeric (alphabets or numbers). We can iterate through each character in the string, retaining only alphanumeric characters and spaces.

READ:  Isdecimal method in Python String

Here is an example to remove special characters except for space from a string in Python using the str.isalnum() function.

Code:

def remove_special_characters(text):
    return ''.join(char for char in text if char.isalnum() or char.isspace())

text = "The Grand #Canyon—a bucket_ list must- see!"
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: The Grand Canyona bucket list must see

Here’s a screenshot showcasing my Python code in Visual Studio.

How to remove special characters except space from a string in python

How to remove special characters except space using re.split() function

The re.split() function splits a string based on a specified pattern in Python. We can utilize this function to split the string into substrings containing only alphanumeric characters and spaces, effectively removing special characters.

Here’s a simple example:

Code:

import re

def remove_special_characters(text):
    return ' '.join(re.split(r'\W+', text))

text = "Hot dogs ,and baseball at @Yankee Stadium—perfect summer nights!"
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Hot dogs and baseball at Yankee Stadium perfect summer nights 

Included is a screenshot displaying my Python code from Visual Studio.

How to remove special characters from string Python

Python remove special characters from a string using replace()

The replace() method in Python allows us to replace occurrences of a specified substring with another.

Here’s is how we can employ this method to remove special characters except for space from a string in Python.

Code:

def remove_special_characters(text):
    special_chars = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
    for char in special_chars:
        text = text.replace(char, '')

    return text

text = "@Golden Gate Bridge #offers stunning San -Francisco views!"
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Golden Gate Bridge offers stunning San Francisco views

Here’s a screenshot of my Python code running in Visual Studio.

Remove special characters from a string except space in Python

How to remove special characters except space using join + generator

Combining the join() method with a generator in Python allows us to create a new string consisting of only alphanumeric characters and spaces, effectively removing special characters.

READ:  Python Read Excel File and Write to Excel File in Python

Let’s see an example:

Code:

to_remove = [';', ':', '!', "*","@","."]
text = "Visit the Smithsonian Museum in @D.C. for !American history treasures!"
print("Original String : " + text)
text = ''.join(i for i in text if not i in to_remove)
print("Cleaned Data : " + str(text))

Output:

Original String : Visit the Smithsonian Museum in @D.C. for !American history treasures!
Cleaned Data : Visit the Smithsonian Museum in DC for American history treasures

Attached is a screenshot of my Python code in Visual Studio.

How to remove special characters from string except space in Python

Remove special characters from a string except space using findall() function

The findall() function from the re module returns all non-repeated matches of a pattern in a string as a list of strings in Python. This function can find all alphanumeric substrings and spaces in the string.

Presented below is a simple example to remove special characters except for space from a string in Python:

Code:

import re

def remove_special_characters(text):
    return ''.join(re.findall(r'[a-zA-Z0-9\s]', text))

text = "Route '66—th' ultimate #American road trip!"
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Route 66th ultimate American road trip

Displayed below is a screenshot of my Python code from Visual Studio.

remove special characters from string python

Python remove Special Characters from a string using translate()

The translate() method in Python maps one set of characters to another.

The maketrans() function creates a translation table where each character in the first argument is mapped to the corresponding character in the second argument in Python.

Code:

def remove_special_characters(text):
    translation_table = str.maketrans('', '', "!@#$%^&*()_+<>?:{}|~`")
    cleaned_text = text.translate(translation_table)
    return cleaned_text

text = "Mount #Rushmore showcases $four iconic @presidents!"

cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Mount Rushmore showcases four iconic presidents

Presented is a screenshot showing my Python code in Visual Studio.

How to Remove All Special Characters from a String except space in Python

Remove special characters from a string using filter() method in Python

We can use the filter() method, which is a built-in method of Python, and it creates an iterator that retains only alphanumeric characters and spaces from a string.

READ:  How to Send email using Python?

Here’s how you can use it:

Code:

def remove_special_characters(text):
    return ''.join(filter(lambda char: char.isalnum() or char.isspace(), text))

text = "Welcome! To the (USA)."
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Welcome To the USA

Here’s a screenshot of my Python code executed in Visual Studio.

Python Remove Special Characters from a String

Using Map and lambda function to remove special characters from a string

The map() function applies a function to each element of an iterable, producing a new iterable in Python. Also, we are using the lambda function with map() to iterate over each character in the input string.

Let’s take one example to remove special characters except for space from a string in Python.

Code:

def remove_special_characters(text):
    special_chars = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
    cleaned_text = ''.join(map(lambda char: '' if char in special_chars else char, text))
    return cleaned_text

text = "Fireworks on the '@Fourth of July light' up the sky with '#bursts' of red, white, and blue!"
cleaned_text = remove_special_characters(text)
print("Cleaned Text:", cleaned_text)

Output

Cleaned Text: Fireworks on the Fourth of July light up the sky with bursts of red white and blue

Displayed is a screenshot of my Python code running in Visual Studio.

How to remove special characters but not spaces in Python

Conclusion

In conclusion, we learned 9 easy ways to remove special characters except for space from a string in Python. These methods are useful for data cleaning, ensuring that only relevant information remains for analysis or processing.

We explored techniques such as using regular expressions with re.sub(), re.split(), and findall() functions, and string methods like replace() and isalnum().

We can also combine the join() method with generator expressions and filter() and map() with lambda functions, we efficiently achieved our goal to remove special characters except space from string in Python.

You may also like to read: