
使用 `readlines()` 读取文件时,每行末尾默认包含换行符 `\n`,导致拼接字符串时内容被强制换行;解决方法是调用 `.strip()` 去除首尾空白(包括换行符),再进行字符串拼接。
当你使用 open('wordlist.txt').readlines() 读取文件时,Python 会将每一行(包括其末尾的换行符 \n)作为独立字符串存入列表。因此,random.choice(...) 返回的 random_line 实际值类似 "f2kd\n",而非 "f2kd"。执行 print(random_line + "This does not appear on same line") 时,\n 会立即触发换行,使后续文本出现在下一行。
✅ 正确做法是使用 .strip() 清除行末(及行首)的空白字符(含 \n, \r, \t, 空格等):
import random
random_line = random.choice(open('wordlist.txt').readlines())
print(random_line.strip() + "This appears on the same line")⚠️ 注意事项:
- 避免重复调用 print():原示例中误写为 print(print(...)),会导致 None 被打印,应仅保留一层 print()。
- 推荐使用上下文管理器(with 语句)安全读取文件,防止资源泄露:
import random
with open('wordlist.txt', 'r', encoding='utf-8') as f:
random_line = random.choice(f.readlines())
print(random_line.strip() + "This appears on the same line")? 进阶提示:若只需随机一行且文件较大,可考虑 linecache.getline() 或逐行迭代+蓄水池采样以节省内存;但对一般词表文件,readlines() + strip() 已足够高效、清晰。










