I'm trying to remove white spaces before and after a phrase which is placed inside double quotation marks. Whatever I've found on google removes the spaces alright but removes the spaces before and after the quotation marks too.
txt = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."
# output:
"election laws\"are outmoded or inadequate and often ambiguous\"and should be changed."
This is the code:
import re
regex = r"(?<=[\"]) +| +(?=[\"])"
test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)
if result:
print (result)
The expected output is:
"election laws \"are outmoded or inadequate and often ambiguous\" and should be changed."
Please help.
The modified version of your code to work is:
import re
regex = '\\"\s+([^"]+)\s+\\"'
test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed \" second quotes \"."
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, '\"'+r'\1'+'\"' , test_str)
if result:
print (result)
output:
election laws "are outmoded or inadequate and often ambiguous" and should be changed "second quotes".
Explanation: I replace a match of \" + spaces + (anything) + spaces + \" with \"+(anything)+\" where the () means capture group. So I can reference this capture group using the syntax r'\1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With