One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub('['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Answer from Kobi K on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-removing-unwanted-characters-from-string
Remove Special Characters from String in Python - GeeksforGeeks
July 11, 2025 - Explanation: re.sub() function replaces all non-alphanumeric characters matched by the pattern [^a-zA-Z0-9] with an empty string, leaving only letters and digits in the result. str.isalnum() method checks if a character is alphanumeric (letters ...
Discussions

Special Characters in str.replace()
You need to escape characters that hold special meaning (eg. [] denotes a character group in regex). To escape them (ie. making them behave like normal characters) you put a backslash in front of them: [ -> \[ ] -> \] " -> \" \ -> \\ More on reddit.com
🌐 r/learnpython
6
2
July 24, 2022
Special characters in Python string replace - Stack Overflow
I have a string in python I want to replace any special characters in that string. I have done like below col_name = 'AN*_Gen_**Air_&Outlet_$Temp' reps = (('_&', ' '), ('*_', '('), (... More on stackoverflow.com
🌐 stackoverflow.com
string - Replace special characters in python - Stack Overflow
Got "Timestamp conversion failed" when I tried to use "set_position()" to play a streaming video using python-vlc ... LLMs and "preferred form.. for making modifications" What are the bonus 15 minutes in the extended version of Backrooms? More on stackoverflow.com
🌐 stackoverflow.com
How to replace all those Special Characters with white spaces in python? - Stack Overflow
How to replace all those special characters with white spaces in python ? I have a list of names of a company . . . Ex:-[myfiles.txt] MY company.INC Old Wine pvt master-minds ltd ... More on stackoverflow.com
🌐 stackoverflow.com
January 10, 2012
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python regex replace special characters
Python regex replace special characters - Spark By {Examples}
May 31, 2024 - How to replace special characters in Python using regex? As you are working with strings, you might find yourself in a situation where you want to replace
🌐
Medium
medium.com › @blueberry92450 › three-ways-to-remove-special-characters-from-string-in-python-da1035cc93b8
Three ways to Remove Special Characters from String in Python Including Time Comparison | Medium
August 8, 2022 - def replace_symbol(filename): for symbol in ['*', '?', '%', '&', '$', '(', ')', '#', '^', '@', '!', '~', '-', '+', '=', " ", ",", "'", '"',"/", "."]: if symbol in filename: filename = filename.replace(symbol, '') return filename ... %timeit string_filtered = replace_symbol(string) # returns: 885 ns ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)print(f”replace: {string_filtered}”) # returns: replace: HelloImSharon ... If you are fully aware of the character type range of the content you are dealing with and you want to replace specific characters with other character => make your own customized replace function
🌐
Reddit
reddit.com › r/learnpython › special characters in str.replace()
r/learnpython on Reddit: Special Characters in str.replace()
July 24, 2022 -

I have the following code.

The aim is to remove all special characters from the column of a DataFrame, although it does not matter if all special characters are removed from the DataFrame.

The code i have used is:

words = combined_body_title.title_body.str.split().explode().str.replace("[?.',)(/:!]","", regex=True)

This works until i put in quotation markets or brackets.

I have read the documentation, from that i think i am using it wrong. I should not be trying to change more than one character within the str.replace, but for some reason it still works just not for brackets and quotation marks.

If you could suggest an alternative solution or help me fix this one i would really appreciate it!

🌐
Coderanch
coderanch.com › t › 709349 › languages › Replace-special-characters
Replace special characters [Solved] (Jython/Python forum at Coderanch)
Thank you in advance for your help ... Which Python version are you using? If you're using Python 2, strings are not automatically Unicode. Try using s = s.replace(u'ç', '') - the u tells Python that it's a Unicode string.
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-string-replace-special-characters-with-space-exampleexample.html
Python String Replace Special Characters with Space Example - ItSolutionstuff.com
October 30, 2023 - import re # Declare String Variable myString = "Hello@, This is It-Solution-Stuff.com. This is awesome.!" # Python String Replace Special Characters with Space replaceString = re.sub('[^a-zA-Z0-9 \n\.]', '', myString) print(replaceString)
Find elsewhere
🌐
Talkerscode
talkerscode.com › howto › replace-special-characters-in-python.php
Replace Special Characters In Python - TalkersCode.com
Regex patterns are supported by Python's regex module (re), which includes the function sub() that replaces string contents with patterns. A character can be completely replaced throughout the string by using the re.sub() function.
🌐
StrataScratch
stratascratch.com › blog › how-to-replace-a-character-in-a-python-string
How to Replace a Character in a Python String - StrataScratch
October 18, 2024 - After importing the re module, we create the ‘python1234string’ string. Then we use the re.sub() method to replace all digits with ‘X’. Here, \d is a shorthand for the class [0-9], and r denotes a raw string, which ensures special characters are treated literally. This means \n is not treated as an escape sequence representing a newline, but literally. The s argument in ...
🌐
Netlify
ittutoria-removechar.netlify.app
Remove Special Characters From String Python
[aZA-Z0-9] will be the regular expression. is any character that is not in brackets. import re string = input('Enter any string: ') new_string = re.sub(r'[^a-zA-Z0-9]','',string) print('New string:', new_string) ... The Replace() method can be used to replace any substrings. This is an integrated ...
🌐
Quora
quora.com › In-Python-how-do-I-use-the-replace-function-on-strings-to-replace-multiple-characters-e-g-a-space-or-any-special-character-with-the-empty-string-E-g-Tes-ting-replace-only-replaces-the-space-not-the
In Python, how do I use the .replace() function on strings to replace multiple characters, e.g. a space or any special character, with th...
Answer (1 of 4): Why do you ask how to use a function (method) to do something after you’ve already demonstrated to yourself that the function/method doesn’t do that? Perhaps it’s better to describe what you want to accomplish and ask which functions or methods might already exist to ...
Top answer
1 of 2
7

If, s=url['title'] makes s equal to this:

In [48]: s=u'Oscar Winners Best Pictures Box Set \xc2\xa36.49'

Then the problem is

  1. in the code that defines url,
  2. or else the content from the web is mal-formed.

If Case 1, we'd need to see the code that defines url.

If Case 2, a quick-and-dirty workaround would be to encode the unicode object s with the raw-unicode-escape codec:

In [49]: print(s)
Oscar Winners Best Pictures Box Set £6.49

In [50]: print(s.encode('raw-unicode-escape'))
Oscar Winners Best Pictures Box Set £6.49

See also this SO question.


Regarding titles like s=u'Star Trek XI £3.99': Again, it would be nice fix the problem before it gets to this stage -- perhaps by looking at how url is defined. But assuming the content from the web is mal-formed, a workaround would be:

In [86]: import re

In [87]: print(re.sub(r'&#x([a-fA-F\d]+);',lambda m: unichr(int(m.group(1),base=16)),s))
Star Trek XI £3.99

A little bit of explanation:

Note that

In [51]: x=u'£'
In [53]: x.encode('utf-8')
Out[53]: '\xc2\xa3'

So the unicode object u'£', encoded with the utf-8 codec, becomes the string object '\xc2\xa3'.

Somehow, url['title'] is getting defined to be the unicode object u'\xc2\xa3'. (The u makes a big difference!)

Thus we have u'\xc2\xa3' when we desire '\xc2\xa3'. Encoding the unicode object u'\xc2\xa3' with the raw-unicode-escape codec transforms it to '\xc2\xa3'.

2 of 2
0

Edit: you have your objects already in unicode. Seems to me there is no reason to actually use enocde/decode at all.

>>> print u'Oscar Winners Best Pictures Box Set \xc2\xa36.49'.replace(u'Â','')
Oscar Winners Best Pictures Box Set £6.49

However it seems to me that something is wrong there. The unicode objects are actually not unicode; see:

>>> print 'Oscar Winners Best Pictures Box Set \xc2\xa36.49'.decode('utf8')
Oscar Winners Best Pictures Box Set £6.49

The repr() you posted should not be unicode object. That's why I was asking where are you getting the data, there is something wrong.

🌐
Delft Stack
delftstack.com › home › howto › python › remove special characters from string python
How to Remove Special Characters From the String in Python | Delft Stack
February 2, 2024 - Python’s built-in re module provides functions for working with regular expressions. ... import re # Example string with special characters original_string = "Hey! What's up bro?" # Define the regular expression pattern for non-alphanumeric characters pattern = r"[^a-zA-Z0-9\s]" # Use re.sub() to replace special characters with an empty string cleaned_string = re.sub(pattern, "", original_string) # Print the cleaned string print("Original String:", original_string) print("Cleaned String:", cleaned_string)
🌐
Scaler
scaler.com › home › topics › remove special characters from string python
Remove Special Characters From String Python - Scaler Topics
January 6, 2024 - To remove special characters from a string in python, we can use the re.sub() method. The method has the following syntax, The regex_pattern is the regex pattern used to match characters in a string. The replace_char is the character we will replace with the characters matching the regex pattern.
🌐
Linux Hint
linuxhint.com › remove-special-characters-string-python-2
Remove Special Characters from String Python – Linux Hint
To get the string without any special character in Python, the “re.sub()” method can also be utilized. The “re” regular expressions are used for identifying the special character from the provided string and the “re.sub” method replaces these unwanted string characters.