简体   繁体   中英

In Python, printing a newline when a word is in line

I wanna print a '\\n' to separate the lines when a specific word is found. This is what i did:

with open('test.txt') as my_file:
   match = False
   for line in my_file:
       if 'location'  in line:
           print('\n')
       if 'text1' in line:
           match = True
       elif 'text3' in line:
           match = False
       elif match:
            print(" ".join(line.split()))

But this prints before the word 'location'. For example:

text1

location
text2

I want it to print as such:

text1
location

text2
with open('test.txt') as my_file:
   for line in my_file:
       print(line)
       if 'location'  in line:
           print('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM