1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.