【问题标题】:How do I read a string portion until the end of line [closed]如何读取字符串部分直到行尾[关闭]
【发布时间】:2020-07-07 08:53:10
【问题描述】:

我的 txt 文件包含:

Match 30, Rajiv Gandhi Intl. Cricket Stadium, Hyderabad
Delhi Capitals won by 39 runs
Sunrisers Hyderabad

我想从体育场读到行尾

所以输出应该是

Stadium, Hyderabad

并且想要为多行执行此操作,所有行都从特定单词开始打印到行尾

我该怎么做

【问题讨论】:

  • 能否分享一下代码或txt文件。
  • 到目前为止你有什么尝试?

标签: python python-3.x string


【解决方案1】:

您可以通过字符串的find() 方法并从创建的索引切线到末尾来做到这一点。

lines = """
Match 30, Rajiv Gandhi Intl. Cricket Stadium, Hyderabad  
Delhi Capitals won by 39 runs  
Sunrisers Hyderabad
"""

for line in lines.split("\n"):
    if "Stadium" in line:
        print(line[line.find("Stadium"):])

从文件中

with open(full_file_path) as f:
    lines = f.readlines()
for line in lines:
    if "Stadium" in line:
        print(line[line.find("Stadium"):])

输出

Stadium, Hyderabad  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2014-07-06
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多