Nupur Kulkarni
Nupur Kulkarni

Reputation: 63

Ignore specific part of string in python

My String is

I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny

So I don't want to replace "Destiny" from

TAG:{Destiny2,the last Destiny game}     

but I want to replace last word "Destiny" with

TAG:{Destiny:Destiny}    

I always want to ignore string in TAG while replacing.

Expected Output:

I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny:Destiny}

Please help.

Upvotes: 1

Views: 2423

Answers (2)

Willian Vieira
Willian Vieira

Reputation: 736

import re

my_string='I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny'

match = lambda x: True if len(re.split('(Destiny){1}', x)) == 3 else False 
repl =  lambda x: str.replace(x,'Destiny','TAG:{Destiny:Destiny}') if match(x) else x

l =re.split(r'({.*?})',my_string)
replaced=[repl(i) for i in l]
print(''.join(replaced))

output

I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny:Destiny}

Upvotes: 0

Jack Taylor
Jack Taylor

Reputation: 6207

You need to parse your string first to find out which Destiny substrings are inside a tag, and which aren't. I have done this below with re.split.

My use of re.split returns a list of substrings surrounding the regex pattern TAG:?{.*?}, and because I enclose the pattern in parentheses, the tags are included in the list as well. In this use of re.split, the non-tags will always have an even index, and the tags will always have an odd index. So I check if the index is even, and if so I replace Destiny with TAG:{Destiny,Destiny}.

import re

s = 'TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny'
result = []
for i, substring in enumerate(re.split('(TAG:?{.*?})', s)):
    if i % 2 == 0:
        substring = substring.replace('Destiny', 'TAG:{Destiny,Destiny}')
    result.append(substring)
result = ''.join(result)
print(result) # TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny,Destiny}

This will work as long as you don't have tags nested inside other tags.

Upvotes: 2

Related Questions