하나의 간단한 해결책은 다음과 같습니다 : 그들이 각각 라인의 시작과 끝에서 f를, 당신은 정규식을 사용할 수 있습니다. 코드에는 각 코드 행을 이해할 수 있도록 많은 설명이 포함되어 있습니다. 뷰티 코드는 연산자를 사용하여 예외를 처리하고 리소스 (예 : 파일)를 닫습니다.
#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
실제로 작동합니다. 감사! – yamdoot