一个简单的解决方案如下所示。代码包含许多注释,使您能够理解每一行代码。代码的优点是,它使用with运算符来处理异常并关闭资源(如文件)。#Specify the absolute path to the input file.
file_path = "input.txt"
#Open the file in read mode. with operator is used to take care of try..except..finally block.
with open(file_path, "r") as f:
'''Read the contents of file. Be careful here as this will read the entire file into memory.
If file is too large prefer iterating over file object
'''
content = f.read()
size = len(content)
start =0
while start < size:
# Read the starting index of & after the last ! index.
start = content.find("&",start)
# If found, continue else go to end of contents (this is just to avoid writing if statements.
start = start if start != -1 else size
# Read the starting index of ! after the last $ index.
end = content.find("!", start)
# Again, if found, continue else go to end of contents (this is just to avoid writing if statements.
end = end if end != -1 else size
'''print the contents between $ and ! (excluding both these operators.
If no ! character is found, print till the end of file.
'''
print content[start+1:end]
# Move forward our cursor after the position of ! character.
start = end + 1