How to use regex sub to replace a substring?

Question:

My questions is how can I use regex sub in a way that the substituted substring is obtained by mutating the matched part?
Let me explain
if original string is "The most comment log in coding is Hello World"
then the modified string should be "The1 most comment log in coding is Hello1 World1"

lets say regex is r'[A-Z][a-z]+'

How can I add something after or importantly in-between each match?

Please help me out here

I have tried regex sub, split etc

Asked By: Ammar Ibraheem

||

Answers:

This should do the trick but you would need to provide a string

suffix="1"
x = "The most comment log in coding is Hello World"
for i in re.finditer('[A-Z][a-z]+', x):
    x = x.replace(i.group(), f"{i.group()}{suffix}")
print(x)

output

The1 most comment log in coding is Hello1 World1
Answered By: anmol_gorakshakar

It appears that you only wish to append the value where the word starts with a capital letter, this is an assumption but if so something like this would be fit;

import regex as re
startingString = "The most comment log in coding is Hello World"
appendedValue = "1"
pattern = re.compile(r'b[A-Z]w*b')
print(pattern.sub(r'g<0>'+appendedValue, startingString))

Output:

The1 most comment log in coding is Hello1 World1
Answered By: Madison Courto

You could use g<0> to refer to the full match, and then append 1 after it.

import re
s = "The most comment log in coding is Hello World"
print(re.sub(r"[A-Z][a-z]+", r"g<0>1", s))

Output

The1 most comment log in coding is Hello1 World1
Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.