0

I'm trying to replace the substring 'gta' with substring 'cat'. But the condition is that 'gta' immediately has to be followed by substring 'dog'.

Example: 'gtagtadogcat' would become 'gtacatdogcat'

The part I'm struggling with is trying to write the program to find 'gta' and validate that 'dog' is behind it and if true, change 'gta' to 'cat'.

DKill
  • 3
  • 3
  • you could take a look at regular expressions in python if you wanted the most flexible way of doing substring replacements. Take a look at this: https://stackoverflow.com/questions/5658369/how-to-input-a-regex-in-string-replace – Lingster Oct 17 '18 at 20:29
  • ...in other words, you're trying to replace `gtadog` with `catdog`. – Gerrat Oct 17 '18 at 20:32

3 Answers3

2
>>> 'gtagtadogcat'.replace('gta'+'dog', 'cat'+'dog')
'gtacatdogcat'
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0
old_string = 'gtagtadogcat'
print(old_string.replace('gtacat','dogcat'))

output: gtagtadogcat

xyz
  • 306
  • 3
  • 11
0

You could use regex:

re.sub('gta(dog)', r'cat\1', 'gtagtadogcat')

Output:

'gtacatdogcat'


*Edit: You would not need a forloop if you put in the whole string. Here is an example:

re.sub('gta(dog)', r'cat\1', 'gtagtadogcat_moretextgta_lastgtadog')

Output:

'gtacatdogcat_moretextgta_lastcatdog'
Joe Patten
  • 1,664
  • 1
  • 9
  • 15
  • Thanks for the comments. I forgot to mention that the Example was just one combination of what could be put in. I need to make sure that if dog comes up multiple times, and if there's a 'gta' in front of it, it'll change it to 'cat'. The example I gave just has it coming up once. Would I need a For loop to cycle through the string in that regard? – DKill Oct 18 '18 at 03:10
  • I have edited my post. – Joe Patten Oct 18 '18 at 15:41