-1

I am trying to find the most efficient way natural to Python, to find all instances of a string within another string surrounded by a $$ sign and replace it with another value in another variable.

The string in question is like this "$$firstOccurance$$ some other words here then $$secondOccurance$$"

My solution below is not working, I think because it's not able to differentiate between the first time it finds the $$ sign and the second time it finds it again. This results in nothing getting printed. There can be many occurrences of strings between the $$ value.

the_long_string = "$$firstOccurance$$ some other words here then $$secondOccurance$$"
replacement_value = "someNewString"
print(the_long_string[the_long_string.index('$$')+len('$$'):the_long_string.index('$$')])

What would be the way to correct and fix what I have done so far? The end result has to look like this someNewString some other words here then someNewString, where there is no $$ sign left.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user20358
  • 14,182
  • 36
  • 114
  • 186
  • 1
    You can find an index starting from a given position, read [the docs](https://docs.python.org/3/library/stdtypes.html#str.index). But maybe this is a job for a [regular expression](https://stackoverflow.com/questions/4736/learning-regular-expressions)? – jonrsharpe Feb 06 '23 at 22:18
  • This replacement value should replace those between `$$`? – Anoushiravan R Feb 06 '23 at 22:19
  • @AnoushiravanR yes it should. – user20358 Feb 06 '23 at 23:23

2 Answers2

2

You would use a regular expression substitution:

re.sub(r'\$\$\w+\$\$', replacement_value, the_long_string)

mbuchove
  • 33
  • 5
1

Here is a complete example building on @mbuchove's example. Use the regex package (re) to make it easier for you.

The key is you need to use re.sub() to find and replace all matches.

import re

the_long_string = "$$firstOccurance$$ some other words here then $$secondOccurance$$"
replacement_value = "someNewString"
the_long_string = re.sub("\$\$\w+\$\$", replacement_value, the_long_string)

print(the_long_string)

If you want to continue with the search manually (without regex), you would need to do something a lot more complicated, still finding all of the $$[n]Occurence$$ by hand.

prev_index = -1
search_start = 0
index = the_long_string.find("$$", search_start)
while index != -1:
    print(index)

    # Closing set of $$
    if prev_index != -1:
        end_index = index + len("$$")
        value_to_replace = the_long_string[prev_index:end_index]
        the_long_string = the_long_string.replace(value_to_replace, replacement_value)
        prev_index = -1 # Reset the search for an opening set of $$
        
    # Opening set of $$
    else:
        prev_index = index
    
    # Check for the next match
    search_start = index + len("$$")
    index = the_long_string.find("$$", search_start)
print(the_long_string)
tkawchak
  • 24
  • 3