簡體   English   中英

在 Python 中,當單詞在行中時打印換行符

[英]In Python, printing a newline when a word is in line

當找到特定單詞時,我想打印一個 '\\n' 來分隔行。 這就是我所做的:

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()))

但這會打印在“位置”一詞之前。 例如:

text1

location
text2

我希望它打印如下:

text1
location

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM