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\.]
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!
Replace special characters in a string in Python - Stack Overflow
Special characters replace using regex in python - Stack Overflow
Python Regex to replace whole word including some special characters - Stack Overflow
Regular Expression: Replacing Special Characters and ONLY \n (not Word Spacing) from a String
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\.]
str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
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.
You could use re.escape to escape all the special regex characters in the string, and then enclose the escaped string into [...] so it matches any of them.
>>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?/\''), '_', table)
'123____________|___"_______\\__,__'
However, as you are not really using that regex as a regex, you might instead just check whether each character is in that string:
>>>''.join("_" if c in '!~@#$%^&*()-+={}[]:;<.>?/\'' else c for c in table)
'123____________|___"_______\\__,__'
Or to make the lookup a bit faster, create a set from the chars in that string first:
>>> bad_chars = set('!~@#$%^&*()-+={}[]:;<.>?/\'')
>>> ''.join("_" if c in bad_chars else c for c in table)
Just put it in a character class and rearrange the position of some characters (namely -, escaping +):
import re
table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""
table1 = re.sub(r'[-\+!~@#$%^&*()={}\[\]:;<.>?/\'"]', '_', table)
print(table1)
# 123____________|___________\__,__
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})'\))
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)
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!