【问题标题】:Print next characters in line Python在 Python 行中打印下一个字符
【发布时间】:2016-02-08 17:15:54
【问题描述】:

我正在寻找一个简单的程序来查找一个字符,然后打印该行中接下来的 10 个字符。我只能让它打印出整行,其余的行是无用的。这就是我现在所拥有的。

f = open("Active Notship.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "P-" in line:
        print line

【问题讨论】:

  • 尝试使用find和切片。
  • 试试print line[line.find("P-")+2 : line.find("P-")+12]

标签: python python-2.7 search text


【解决方案1】:

凯文是对的。这就是我所做的。

f = open("Active Notship.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "P-" in line:
        print line[3:13]

【讨论】:

  • 如果"P-" 不在行首,这将不起作用。请参阅我的评论。
【解决方案2】:

除了find 和切片之外,您还可以使用regular expression

text = """some text
with many lines
some have a P- and some stuff behind it
like this: P- foo
and others don't
"""

import re
print(re.findall("(?<=P-).{1,10}", text))

输出:[' and some ', ' foo']

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2018-08-11
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2020-11-06
    • 2021-12-12
    相关资源
    最近更新 更多