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
๐ŸŒ
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
๐ŸŒ
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 special characters in a string in Python - Stack Overflow
This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space. ... Are you sure regex will perform better than translate? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Special characters replace using regex in python - Stack Overflow
There's also \W, which matches-all non-word characters: re.sub(r'\W', '_', some_string). docs.python.org/3/library/re.html#regular-expression-syntax ... @Blurp Good point, but that would also replace e.g. whitespace. Might use something like [^\w\s] though, depending on what exactly OP wants to replace. Also, there seem to be chars like | what shall not be replaced (might be a mistake in the question, though). ... You could use re.escape to escape all the special regex ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 14, 2017
Python Regex to replace whole word including some special characters - Stack Overflow
1 Python regex: Replace individual characters in a match ยท 11 replace multiple occurrences of any special character by one in python More on stackoverflow.com
๐ŸŒ stackoverflow.com
Regular Expression: Replacing Special Characters and ONLY \n (not Word Spacing) from a String
You can put \n and \r into their own set of characters to explicitly match them: re.sub('[^a-zA-Z0-9\s]|[\r\n]', '', ss) Note, however, that if you simply remove all punctuation and newlines, then the last word of a line and the first word of the next line will fuse together. So it might make more sense anyway to instead replace newlines with spaces in a separate step. More on reddit.com
๐ŸŒ r/learnpython
1
2
September 29, 2021
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ python string tutorial โ€บ python regex replace
Python regex replace | Learn the Parameters of Python regex replace
May 13, 2024 - In Python, we use replace() function ... to obtain the modified string. This is mainly used for replacing special characters with spaces or some other characters to make the string readable. This is a guide to Python regex replace....
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
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 ...
Top answer
1 of 2
1

You can use a look-around method to insert the /user/ dynamically:

(?<=url\(')/*(?=(?:.*?Inter\.ttf)'\))

And then use re.sub to replace with /user/:

strings = ["url('Inter.ttf')", "url('/hello/Inter.ttf')"]

p = re.compile(r"(?<=url\(')/?(?=(?:.*?Inter\.ttf)'\))")

for s in strings:
    s = re.sub(p, "/user/", s)
    print(s)
url('user/Inter.ttf')
url('user/hello/Inter.ttf')

Pattern Explanation

(?<=url\('): Positive lookbehind; matches strings that come after a string like url('.

/?: Matches zero or one forward slashes /. This is important for matching paths like /hello/Inter.ttf because it starts with the /. This is going to be selected and replaced with the ending forward slash in the replacement string, /user/.

(?=(?:.*?Inter.ttf)'\): Positive lookahead; matches strings that come before a string that ends with Inter.ttf').

I suggest playing around with it on https://regex101.com, selecting the Substitution method on the left-hand-side.

Edit

If you want to match multiple fonts, you can just remove the Inter.ttf part of the regex:

(?<=url\(')/?(?=(?:.*?)'\))

Alternatively, if you wanted it to append /user/ to paths that had a file extension, you can replace Inter\.ttf with \.\w{3}, which effectively matches 3 of any character in [a-zA-Z0-9_]:

(?<=url\(')/?(?=(?:.*?\.\w{3})'\))
2 of 2
0

a simple way to do that is like this without regex:

fin = open("input.css", "rt")
fout = open("out.css", "wt")
for line in fin:
    if "'Inter.ttf'" in line:
        fout.write(line.replace("'Inter.ttf'", "'/user/Inter.ttf'"))
    elif "'/hello/Inter.ttf'" in line:
        fout.write(line.replace("'/hello/Inter.ttf'", "'/user/hello/Inter.ttf'"))
    else:
        fout.write(line)
๐ŸŒ
datagy
datagy.io โ€บ home โ€บ python posts โ€บ python strings โ€บ python: remove special characters from a string
Python: Remove Special Characters from a String โ€ข datagy
December 17, 2022 - One of these methods is the .sub() method that allows us to substitute strings with another string. One of the perks of the re library is that we donโ€™t need to specify exactly what character we want to replace.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ regular expression: replacing special characters and only \n (not word spacing) from a string
r/learnpython on Reddit: Regular Expression: Replacing Special Characters and ONLY \n (not Word Spacing) from a String
September 29, 2021 -

Hi,

I tried to replace spl characters and new line character( \n) but not the word spacing from a sentence.

I want to build one Single regular expression to achieve this.

I tried to use double negation to target only the newline character, but no success.

Giving below my attempt:

ss = """Nory was a Catholic because her mother was a Catholic,and Nory's mother was a Catholic because her father was a Catholic,and her father was a Catholic because his mother was a Catholic,or had been."""

re.sub('[^a-zA-Z0-9\s\r\n]','',ss)

But the output still contains newline character.

output:

'Nory was a Catholic because her mother was a Catholic \nand Norys mother was a Catholic because her father was a Catholic \nand her father was a Catholic because his mother was a Catholic \nor had been'

Could you please help me to correct this?

Thanks in advance!

๐ŸŒ
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 - Letโ€™s break down that regex pattern: - `[^โ€ฆ]` creates a negative set (match anything not in this set) - `a-zA-Z` matches any letter - `0โ€“9` matches any digit - `\s` matches whitespace - The empty string `โ€™โ€™` is what we replace matches with ยท When you need to remove various special characters ...
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ re.html
6.2. re โ€” Regular expression operations โ€” Python 3.4.10 documentation
However, Unicode strings and 8-bit ... when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string. Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to ...
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
StudyMite
studymite.com โ€บ python โ€บ remove-special-characters-from-a-string-in-python-using-regex
Remove Special Characters from a String in Python Using Regex | StudyMite
March 2, 2023 - Learn how to remove special characters from a string in Python using Regex with various methods like using sub(), translate(),replace(),etc
๐ŸŒ
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.
๐ŸŒ
Thedataschool
thedataschool.com โ€บ oksana-kirschbaum โ€บ replace-special-characters-using-regex-in-tableau-alteryx-and-python
Replace special characters using RegEx in Tableau, Alteryx and python - The Data School
In this example we want to replace the distorted german characters into its proper form using Tableau, Alteryx and python. ... In Tableau we can create a Calculated Field and use the REGEXP_Replace function.
๐ŸŒ
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 - In this example, i will add myString variable with hello string. Then we will use sub() function of re library to replace all special characters with space from a string in python.
๐ŸŒ
Community
community.safe.com โ€บ home โ€บ forums โ€บ fme form โ€บ transformers โ€บ regex in stringreplacer for special characters
Regex in StringReplacer for special characters | Community
June 4, 2014 - PythonFactory failed to load python symbol `FeatureProcessor' ... A fatal error has occurred. Check the logfile above for details ยท import fmeobjects import unicodedata as ud def rmdiacritics(char): ''' Return the base character of char, by "removing" any diacritics like accents or curls and strokes and the like.