Search code examples
python-3.xstringreplaceregexp-replace

How to find string that startswith and replaces


I have a file where I need to search for string and replace, difficulty is the string changes as pre-requisite which I'm struggling to get the code working.

Text file: This is a Test file TEST001.

In above text file TEST001 changes the last three integers as part of other functions. How can we find string that starts TEST and relpace with TEST002 ?

Tried multiple ways and failed badly. Any help would be greatly appreciated.

  import re

  target_str = "This is a Test file TEST001 learning"
  res_str = re.sub('^[TEST]' , 'TEST111', target_str)
  # String after replacement
  print(res_str)

Solution

  • You can use pattern \bTEST\d{3}\b -> This will search for TEST and 3 digits. Then use re.sub to replace it:

    import re
    
    target_str = "This is a Test file TEST001 learning"
    res_str = re.sub(r'\bTEST\d{3}\b' , 'TEST111', target_str)
    print(res_str)
    

    Prints:

    This is a Test file TEST111 learning