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

Python字符串范围判断程序输出换行问题求助

Python输出同行显示问题解决

问题原因

你用file.readlines()读取文件内容时,每一行的字符串末尾会自带换行符\n。当直接执行print(contents[i], ' - in range')时,print会先输出带换行的行内容,再输出后面的描述文本,自然就分成了两行。

解决方法

方法1:去除每行末尾的换行符(推荐)

读取行内容后,用rstrip('\n')或strip()去除末尾的换行符,再进行判断和输出:

input_file = input() 
upper = input() 
lower = input() 

with open(input_file, 'r') as f:  
    contents = f.readlines()

for line in contents:
    # rstrip('\n')仅删除末尾换行符,strip()会同时删除首尾所有空白字符
    cleaned_line = line.rstrip('\n')
    if upper <= cleaned_line <= lower:
        print(f"{cleaned_line} - in range")
    else:
        print(f"{cleaned_line} - not in range")

方法2:控制print的换行行为

通过修改print的end参数,覆盖默认的换行逻辑:

input_file = input() 
upper = input() 
lower = input() 

with open(input_file, 'r') as f:  
    contents = f.readlines()

for line in contents:
    if upper <= line <= lower:
        # 先输出去除换行的行内容,再输出描述文本
        print(line.rstrip('\n'), end='')
        print(' - in range')
    else:
        print(line.rstrip('\n'), end='')
        print(' - not in range')

额外优化提示

循环时没必要用range(len(contents)),直接遍历contents中的每一行代码更简洁,可读性也更高。

内容的提问来源于stack exchange,提问作者user22141540

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:03:10