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
🌐
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!

Discussions

replace - replacing special characters in string Python - Stack Overflow
I'm trying to replace special characters in a data frame with unaccented or different ones. More on stackoverflow.com
🌐 stackoverflow.com
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
Python String replacing special characters - Stack Overflow
I need to replace "-" with spaces (but not more than 1 consecutively, and strip everything at the beginning and at the end) and delete any other special character, some examples: "Example-1"... 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
🌐
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 ...
🌐
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.
🌐
Coderanch
coderanch.com › t › 709349 › languages › Replace-special-characters
Replace special characters [Solved] (Jython/Python forum at Coderanch)
Hello everyone, I start in Jython and I would like open a file and replace special characters Here my code : s = open("C:\JYTHON\TEST.xml").read() s = s.replace('&', '') s = s.replace('è', '') s = s.replace('é', '') s = s.replace('*', '') s = s.replace('%', '') s = s.replace('@', '') s = s.replace('ç', '') s = s.replace('à', '') s = s.replace('#', '') s = s.replace('«', '') s = s.replace('»', '') f = open("C:\JYTHON\TEST.xml", 'w') f.write(s) f.close() It works for : & * % &nbsp;# It does not work for : é è ç à << >> In addition, my list may not be exhaustive: ê Ê ... Thank you in advance for your help ... Which Python version are you using? If you're using Python 2, strings are not automatically Unicode.
Find elsewhere
🌐
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 ...
🌐
Medium
medium.com › @ryan_forrester_ › remove-special-characters-from-strings-in-python-complete-guide-53651c8163d9
Remove Special Characters from Strings in Python: Complete Guide | by ryan | Medium
January 7, 2025 - The `replace()` method works well when you know exactly which characters you want to remove. The `strip()` method is perfect for cleaning up the beginning and end of strings. When you need more control over character removal, regular expressions are your friend. Here’s a practical example: import re def clean_text(text): # Removes all special characters except spaces and alphanumeric characters cleaned = re.sub(r'[^a-zA-Z0-9\s]', '', text) return cleaned # Real-world example: Cleaning a product description product_desc = "Latest iPhone 13 Pro (128GB) - $999.99 *Limited Time Offer!*" clean_desc = clean_text(product_desc) print(clean_desc) # Output: "Latest iPhone 13 Pro 128GB 999.99 Limited Time Offer"
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 &#xA3;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.

🌐
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.
🌐
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 - If you want to just remove all kinds of special characters => use filter(str.isalnum, string) 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 · If you have to remain specific characters and replace the rest with other character => use re package · ms: 1/1000 s · μs: 1/1000,000 s · ns: 1/1000,000,000 s · Python ·
🌐
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.
🌐
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 ...