首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中将重复字符串的索引存储在文件中

在python中将重复字符串的索引存储在文件中
EN

Stack Overflow用户
提问于 2018-09-19 00:45:17
回答 1查看 0关注 0票数 0

我正在尝试读取特定字符串的python文件,并将字符串出现的索引存储在另一个变量中。

例如:

student_id("1234", "1345", "1342")
class_enrolled("biology", "math", english)
# Insert 50 lines of code to do something
student_id("2134", "2345", "2342")
class_enrolled("biology", "math", english)
# Insert 50 lines of code to do something
student_id("3134", "3345", "3342")
class_enrolled("biology", "math", english)

总体目标是确定每个学生ID开始的索引,以及每个“class_enrolled”索引的开始位置,以便我只能将学生ID存储在列表中。

我尝试解决方案:

file = open('This is my file').read()
end_of_id_list = []
for ch in file:
    start_list = file.find('student_id')
    end_list = file.find('class_enrolled')
    if end_list != -1:
        end_of_id_list.append(end_list)

这给了我一个无限循环。有没有人对更好的方法有任何建议?如果我的解释不清楚我想要做什么,我会提前道歉。

EN

回答 1

Stack Overflow用户

发布于 2018-09-19 10:30:21

如果最终你只需要学生证,而不关心它们发生在哪里,你可以这样做:

import re
with open('yourfile','r') as f:
    txt=f.read()
re.findall("student_id\(.*?\)",txt)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档