Reputation: 61
I am trying to replace a specific part of my string. Everytime I have a backslash, followed by a capital letter, I want the backslash to be replaced with a tab. Like in this case:
Hello/My daugher/son
The output should look like
Hello My daugher/son
I have tried to use re.sub():
for x in a:
x = re.sub('\/[A-Z]', '\t[A-Z]', x)
But then my output changes into:
Hello [A-Z]y daugher/son
Which is really not what I want. Is there a better way to tackle this, maybe not in regex?
Upvotes: 1
Views: 74
Reputation: 18357
You can replace /(?=[A-Z])
with \t
. Notice in Python you don't need to escape /
as \/
Check this Python code,
import re
s = 'Hello/My daugher/son'
print(re.sub(r'/(?=[A-Z])',r'\t',s))
Prints,
Hello My daugher/son
Alternatively, following the way you were trying to replace, you need to capture the capital letter in a group using /([A-Z])
regex and then replace it with \t\1
to restore what got captured in group1. Check this Python codes,
import re
s = 'Hello/My daugher/son'
print(re.sub(r'/([A-Z])',r'\t\1',s))
Again prints,
Hello My daugher/son
Upvotes: 2