-1

I search with regex

regex has several results

I just want to replace it with my text in a specified index

pattern = '@name'
replace = '*rep*'

text

@name
@name
@name

The result I want index=2

@name
*rep*
@name
Nima
  • 323
  • 4
  • 13

1 Answers1

-1

Using .findall you will get the list, replace the element of a list using prefered index and use .join to get final expected results.

>>> import re
>>> pattern = '@name'
>>> replace = '*rep*'
>>> text = '''@name
@name
@name'''
>>> re.findall(pattern,text)
['@name', '@name', '@name']
>>> index = 2
>>> re.findall(pattern,text)[index-1] = replace # use '-1' as index starts from zero
>>> text_list = re.findall(pattern,text)
>>> text_list[index-1] = replace
>>> ' '.join(text_list)
'@name *rep* @name'
shaik moeed
  • 5,300
  • 1
  • 18
  • 54