0

I have a document.txt that has a line in it that says something like "randomtext here location 34 randomtexthere".

I know how to replace a word with another word but what if I want to replace the random integer after the word "location"? And maybe give an error if there is no integer after the word.

I can't specify the exact number I want to replace because that number can change. So I'm looking for a way to find the number after "location" and change it to the number I specify.

I'm currently working with something like this:

def replaceid():
    source = "C:/mypath/document.txt"
    oldtext = "oldtexthere"
    newtext = "newtexthere"
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(oldtext, newtext), end='')
1
  • I see I can program use split to do this. Any tips on how I can use split properly?
    – Prox
    May 26, 2017 at 2:48

2 Answers 2

3

I can't specify the exact number I want to replace because that number can change

This says you want a regular expression to describe the pattern "a number" without writing any specific number, and to say that it must be found after 'location'".

It might look like this:

import re

s = "randomtext here location 34 randomtexthere"

pattern = r'(?<=location )\d+'       # match a number 
                                     # i.e. a digit (\d) then any more digits (+)
                                     # Only if it comes after 'location '
                                     # (but don't match that word)


if re.search(pattern, s):            # Search for the pattern in the string
  print(re.sub(pattern, '200', s))   # replace the pattern match with new number
else:
  print("Number not found")          # or print an error message

And in your case, do that re.search for each line in the file.

1
  • 1
    Beat me to it and more elegant regex +1 May 26, 2017 at 3:01
0

Something like this, and it could be done shorter (or longer), no function here just an example of replacing the integer with some other random integer. Add more logic if it needs to follow a particular word.

from random import randint

s = "randomtext here location 34 randomtexthere"

l = s.split(' ')
new_l = []
for el in l:
    if el.isdigit():
        new_l.append(randint(0, 99))
    else:
        new_l.append(el)

print(new_l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.