
使用 `readlines()` 读取的每一行末尾默认包含换行符 `n`,导致拼接字符串时内容被强制换行;只需调用 `.strip()` 方法去除首尾空白(含换行符),即可实现同行列印。
当你使用 file.readlines() 读取文本文件时,python 会原样保留每行末尾的换行符 n。因此,即使你只是读取一行并尝试与另一段字符串拼接,n 仍会生效,造成视觉上的“跳行”。
例如,你的原始代码:
import random random_line = random.choice(open('wordlist.txt').readlines()) print(random_line + "This does not appear on same line")
若 random_line 实际值为 “f2kdn”,那么拼接结果就是 “f2kdnThis does not appear on same line” —— n 在中间强制换行,自然无法显示在同一行。
✅ 正确做法是:在拼接前清除换行符。推荐使用 .strip()(安全去除首尾所有空白字符,包括 n、r、t 和空格):
import random with open('wordlist.txt', 'r', encoding='utf-8') as f: random_line = random.choice(f.readlines()).strip() print(random_line + "This appears on the same line")
⚠️ 注意事项:
- 始终优先使用 with open(…) 上下文管理器,确保文件正确关闭,避免资源泄漏;
- 显式指定 encoding=’utf-8′ 可防止中文或特殊字符乱码;
- .strip() 比 .rstrip(‘n’) 更鲁棒(可同时处理 windows rn、mac r 等换行变体);
- end=”” 或 sep=”” 对 print() 本身无效,因为问题根源不在 print 的分隔行为,而在于字符串内部已含 n。
? 小技巧:若需批量处理多行,也可在读取时统一 strip:
lines = [line.strip() for line in open('wordlist.txt')] random_line = random.choice(lines)
总结:readlines() 不“隐藏”换行符——它明确保留它们;这是设计使然,而非 bug。理解并主动清理,是文件行处理的基本功。