如何检查输入值是否存在于文件任意位置并打印?代码优化问询
Fix: Match Lines Containing Pupil ID Anywhere in the File
Hey there, let's get this sorted! Your current code uses line.startswith(pupilEntered2), which only catches lines that begin with the pupil ID you input. That's why it misses lines where the ID is somewhere in the middle (like John34 in your example file).
Here's the adjusted code that will find any line containing the pupil ID, no matter where it shows up:
def uniqueFileSearch(): pupilEntered2 = input("Please enter the pupil ID: \n") with open("pupilInformation.txt", "r") as f: for line in f: # Check if the input ID exists anywhere in the current line if pupilEntered2 in line: print(line.strip()) # Optional: removes extra newlines for cleaner output
Key Changes Explained:
- Replaced
line.startswith(pupilEntered2)withpupilEntered2 in line: This checks if your input ID is present anywhere as a substring in the line, not just at the start. - Added
.strip()to the print statement: This cleans up trailing newline characters, making your output look neater without extra blank lines.
For example, if you input "34" now, the code will correctly print John's line: John34, Ashley, 11, m.
内容的提问来源于stack exchange,提问作者Ben Keez
相关产品推荐
相关产品推荐

