Home > Enterprise >  How can I find all the strings that contains "/1" and remove from a file using Python?
How can I find all the strings that contains "/1" and remove from a file using Python?

Time:09-14

I have this file that contains these kinds of strings "1405079/1" the only common in them is the "/1" at the end. I want to be able to find those strings and remove them, below is sample code but it's not doing anything.

with open("jobstat.txt","r") as jobstat:
    with open("runjob_output.txt", "w") as runjob_output:
        for line in jobstat:
                string_to_replace = ' */1'
                line = line.replace(string_to_replace, " ")

CodePudding user response:

with open("jobstat.txt","r") as jobstat:
    with open("runjob_output.txt", "w") as runjob_output:
        for line in jobstat:
                string_to_replace ='/1' 
                line =line.rstrip(string_to_replace)
                print(line)

CodePudding user response:

Anytime you have a "pattern" you want to match against, use a regular expression. The pattern here, given the information you've provided, is a string with an arbitrary number of digits followed by /1.

You can use re.sub to match against that pattern, and replace instances of it with another string.

import re

original_string= "some random text with 123456/1, and midd42142/1le of words"

pattern = r"\d*\/1"
replacement = ""

re.sub(pattern, replacement, original_string)

Output:

'some random text with , and middle of words'

Replacing instances of the pattern with something else:

>>>  re.sub(pattern, "foo", original_string)
'some random text with foo, and middfoole of words'
  • Related