python - 如何打印从'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 包含所有以“以字符串开头”开头并以“以字符串结尾”结尾的字符串。
解决方案
startswith
并endswith
返回 True 或 False 而不是可以用来分割字符串的位置。尝试find
或index
代替。例如:
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,这将导致一些意外的切片。
推荐阅读
- django - Django REST Serializer 使用错误的模型进行序列化
- python - python文件写入程序运行时如何更新桌面上的文件大小
- javascript - 使用 d3.js 更新表数据
- c# - C#捕获从不在进程中的函数返回的异常?
- r - 如何设置仅在输入 3 时才显示集合向量的函数?
- javascript - 如果 URI 没有改变,例如在单页应用程序上,如何检测用户是否在新页面上?
- angular - Angular Kendo UI 全局访问
- php - 内连接循环通过
- git - 如何 git rebase 从另一个分支直接到 master 分支?
- javascript - 受控数字比例映射