You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查输入值是否存在于文件任意位置并打印?代码优化问询

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) with pupilEntered2 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:32:40