Search code examples
pythonstringtextedit

replacing certain substrings in lines of a text file


Similar questions to this question have been answered before. I want to replace particular substrings in lines of a text file. Based on the answers to similar questions, I came up with the following.

with open('grammars.txt', 'r') as file3:
    # read a list of lines into data
    data = file3.readlines()

mylist = []
# Assuming that you have loaded data into a lines variable. 

  
for line in data:
    if '\n' in line:
        line.strip('\n')
        print('hello')
    if '|' in line:
       line.replace('|','||')
       print('hello')
    if '&' in line:
      line.replace('&','&&')  
      print('hello')
    mylist.append(line)  
print(mylist)

The problem is that when I run this code no changes happen to the strings in data. I tried to use "" instead of '' and searched for possible reasons why this code does not change anything. I made sure that at least in one line of the text file, the condition of at least one of the ifs is met by printing hello. I would appreciate it if you could help me with this. Here is the text file I am using.

NOTE: Once I store the text file lines using readlines(), \n appears at the end of each string which I need to remove.

N0>|,N1,N2&
N1>x0
N2>x1&
-----------------------
N0>U,N1,N2
N1>x1&
N2>x0
-----------------------
N0>U,N1,N3|
N1>G,N2
N2>x1
N3>x0
-----------------------
N0>->,N1,N3
N1>!,N2
N2>x1
N3>x0
-----------------------
N0>U,N3,N2
N3>x1
N2>U,N3,N4
N3>x1
N4>x0
-----------------------
N0>|,N3,N2
N3>x1
N2>U,N3,N4
N3>x1
N4>x0
-----------------------
N0>|,N1,N2
N1>x0
N2>G,N3
N3>x1
-----------------------
N0>U,N4,N2
N4>x0
N2>U,N3,N4
N3>x1
N4>x0
-----------------------
N0>|,N4,N2
N4>x0
N2>U,N3,N4
N3>x1
N4>x0
-----------------------
N0>|,N3,N2
N3>x0
N2>U,N3,N4
N3>x0
N4>x1
----------------------- 

Solution

  • String replace and strip are not in-place. They return a copy of the original string with the modification made.

    with open('grammars.txt', 'r') as file3:
        # read a list of lines into data
        data = file3.readlines()
    
    mylist = []
    # Assuming that you have loaded data into a lines variable. 
    
      
    for line in data:
        if '\n' in line:
            line=line.strip('\n')
            print('hello')
        if '|' in line:
           line=line.replace('|','||')
           print('hello')
        if '&' in line:
          line=line.replace('&','&&')  
          print('hello')
        mylist.append(line)  
    print(mylist)
    

    Most if not all of Python's string-mutating functions work the same way.