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

Python列表元素去除换行符:实现TOKEN无换行拼接

解决Python读取文本后拼接Token的换行问题

问题核心在于readlines()会保留每行末尾的换行符\n,直接拼接Token时,换行符会插在文本和Token之间,导致输出错位。

解决思路

处理每行内容时,先移除末尾的换行符:

  • 若无需保留行首尾其他空白字符,用strip()
  • 若要保留行内首尾空格(比如示例中的多空格分隔符),用rstrip('\n')只删除换行符

修改后的代码

Path = '/Volumes/test_copy.txt'

filename = Path
with open(filename) as file_object:
    # 移除每行末尾的换行符,保留原有空白格式
    lines = [line.rstrip('\n') for line in file_object.readlines()]

# 格式1:文本与Token直接拼接无空格
format1 = ["STARTTOKEN" + item + "ENDTOKEN" for item in lines]
# 格式2:文本与ENDTOKEN之间加空格
format2 = ["STARTTOKEN" + item + " ENDTOKEN" for item in lines] 

# 打印结果
for line in format1:
    print(line)
for line in format2:
    print(line)

输出结果

运行后会得到你期望的两种格式:

STARTTOKENtextprompt     nextelementENDTOKEN # 1. Pref.
STARTTOKENtextprompt     nextelement ENDTOKEN # 2. Pref.

额外优化

如果文本存在空行,可在列表推导式中过滤:

lines = [line.rstrip('\n') for line in file_object.readlines() if line.strip()]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:20:47