Python 3.x Python识别前缀

Python 3.x Python识别前缀,python-3.x,Python 3.x,我是Python的noob,对Python了解不多,但这是最好的猜测,我假设用户输入一年,输入文件输出包含年份的所有年份或至少其前缀,因此我可以输入“1”以及从“1”开始的所有年份会出现…如果你能给我指出正确的方向那就太酷了!提前谢谢 year_input = input("Input a year:") for line in input_file: line = line.strip() year = line[-4:] if len(year_input) ==

我是Python的noob,对Python了解不多,但这是最好的猜测,我假设用户输入一年,输入文件输出包含年份的所有年份或至少其前缀,因此我可以输入“1”以及从“1”开始的所有年份会出现…如果你能给我指出正确的方向那就太酷了!提前谢谢

year_input = input("Input a year:")

for line in input_file:

    line = line.strip()

    year = line[-4:]


if len(year_input) == year or line[-3:] or line[-2:] or line[-1:]:
    prefix = year == line[-3:] == line[-2:] == line[-1:]
    print(prefix) 

您可以使用
startswith
功能,即

for line in input_file:

    line = line.strip()

    year = line[-4:]


    if year.startswith(year_input):
        print(year)

但不是以返回True或False开始吗?if语句恰恰需要这样做。