如何解决如何在具有可重复段落的指定字符串之后读取/修改具有特定位置的行?同时打印所有行
我需要在特定字符串(可能是段落标题)之后修改几行,例如根据行索引位置向行添加制表符空格等前缀。
text = """Para 1
example line one
example blah blah line
example line one
example blah blah line
Some other lines 1
some other lines 2
Para 2
another para line start
another para line start goes
another para line three
another para line four
Para 3
line 1
line 2
line 3
line 4"""
for x in text:
if x == 'Para':
print('Starting specified loop')
for x in text:
if x % 2 == 0: #line 2,4 after string to modify
print('In specified loop ',x)
else:
print("Out Specified loop",x)
else:
print('all other lines',x)
此代码在堆栈中找到并且适用于 xrange 数字,但对于文本它会给出错误。此外,我尝试使用枚举器,但无论行位置如何,它都会打印所有行。我期望在字符串 Para 后修改第 2 行和第 4 行的输出:
Para 1
example line one
example blah blah line
example line one
example blah blah line
Some other lines 1
some other lines 2
Para 2
another para line start
another para line start goes
another para line three
another para line four
Para 3
line 1
line 2
line 3
line 4
希望我已经简要解释了。感谢您的时间和耐心等待回复。
解决方法
text = """
Para 1
line 1
line 2
line 3
line 4
Some other lines 1
some other lines 2
Para 2
line 1
line 2
line 3
line 4
Para 3
line 1
line 2
line 3
line 4
"""
res = text.split("\n")
# print(res)
for each_word in res:
if "line 2" in each_word or "line 4" in each_word:
print " ",each_word
else:
print each_word
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。