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

使用readlines()读取元素后拼接字符串打印换行,如何实现同行输出?

问题描述

尝试在控制台使用print实现同行输出,但始终自动换行。怀疑是读取文件行时携带了隐藏的换行符\n,试过设置end=""、sep=""参数均无效。

代码示例

import random

random_line = random.choice(open('wordlist.txt').readlines())
print((random_line)+"This does not appear on same line")

终端输出

f2kd
This does not appear on same line

解决方法

问题根源确实是readlines()会保留每行末尾的换行符\n,拼接后自然触发换行。以下是几种有效解决方案:

  • 方案1:移除换行符
    对读取到的行调用strip()去除首尾所有空白字符(包括换行符);如果只想保留首尾空格、仅删除换行符,用rstrip('\n')更精准:

    import random
    
    # 去除所有首尾空白
    random_line = random.choice(open('wordlist.txt').readlines()).strip()
    print(random_line + "This does not appear on same line")
    
    # 仅去除末尾换行符
    random_line = random.choice(open('wordlist.txt').readlines()).rstrip('\n')
    print(random_line + "This does not appear on same line")
    
  • 方案2:换用无换行的读取方式
    使用read().splitlines()读取文件,返回的列表中每行都不带换行符,无需额外处理:

    import random
    
    random_line = random.choice(open('wordlist.txt').read().splitlines())
    print(random_line + "This does not appear on same line")
    
  • 方案3:拆分print参数
    将两个输出内容作为print的独立参数,默认用空格分隔,也可通过sep=""取消分隔,同时确保换行符被移除:

    import random
    
    random_line = random.choice(open('wordlist.txt').readlines())
    # 带空格分隔
    print(random_line.rstrip('\n'), "This does not appear on same line")
    # 无空格分隔
    print(random_line.rstrip('\n'), "This does not appear on same line", sep="")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:13:24