Kimi Shui
Kimi Shui

Reputation: 83

Replace the word if it contains certain characters

I have a text file looks like :

a Project[2] 
novel Project[2] 
technique Project[2]
for Project[3] 
extracting Project[3] 
tables Project[3] 
from Project[3] 
lists Project[3]

I need to replace the Project[x] to o.

expected output:

a o
novel o 
technique o
for o 
extracting o 
tables o 
from o 
lists o

instead of using

.replace('Project[2],'o')
.replace('Project[3],'o') 

is there a better way to replace if it contains Project[x]?

Upvotes: 0

Views: 132

Answers (1)

S.B
S.B

Reputation: 16496

You can use regex :

import re

text = """a Project[2] 
novel Project[2] 
technique Project[2]
for Project[3] 
extracting Project[3] 
tables Project[3] 
from Project[3] 
lists Project[3]"""


print(re.sub(r'Project\[\d+\]', 'o', text))

output :

a o 
novel o 
technique o
for o 
extracting o 
tables o 
from o 
lists o

Upvotes: 2

Related Questions