繁体   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