首页 > 解决方案 > 如何打印从'startswith'到'endswith'的部分字符串

问题描述

我喜欢将原始文本文件的一部分(可以在“startswith”和“endswith”字符串之间识别)保存到一个新的文本文件中。

示例:输入文本文件包含以下行:

...abc…
...starts with string...
...def...
...ends with string...
...ghi...

...jkl...
...starts with string...
...mno...
...ends with string...
...pqr...

我有兴趣将以下行提取到输出文本文件中:

starts with string...def...ends with string
starts with string...mno...ends with string

我的以下代码返回空列表 []。请帮助更正我的代码。

with open('file_in.txt','r') as fi:
    id = []
    for ln in fi:
        if ln.startswith("start with string"):
            if ln.endswith("ends with string"):
                id.append(ln[:])
                with open(file_out.txt, 'a', encoding='utf-8') as fo:
                    fo.write (",".join(id))
print(id)

我希望 file.out.txt 包含所有以“以字符串开头”开头并以“以字符串结尾”结尾的字符串。

标签: pythonpython-3.xstartswithends-with

解决方案


startswithendswith返回 True 或 False 而不是可以用来分割字符串的位置。尝试findindex代替。例如:

start = 'starts with string'
end = 'ends with string'
s = '...abc… ...starts with string... ...def... ...ends with string... ...ghi...'

sub = s[s.find(start):s.find(end) + len(end)]
print(sub)
# starts with string... ...def... ...ends with string

您需要在循环中添加一些检查以查看开始和结束字符串是否存在,因为find如果不匹配将返回 -1,这将导致一些意外的切片。


推荐阅读