python - 如何从输出中删除不需要的 '\n'

标签 python python-3.x

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for file_4 in lines:
    number_lines += 1
print(lines)
print(number_lines)

output: ['2\n', '3\n', '4\n', '5']
         4

我的文本文件有 5 行

1
2
3
4
5

我希望输出跳过第一行,并显示其余部分。 如何去掉 /n 以及如何将这些数字打印在不同的行而不是一行上?

最佳答案

最简单的解决方法可能是仅更改 for 循环变量:

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for line in lines:       # do not reuse previous variable here 
    number_lines += 1
    print(line.rstrip()) # strip the newline
print(number_lines)

似乎给出了您的预期输出:

2
3
4
5
4

关于python - 如何从输出中删除不需要的 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823484/

相关文章:

python - 为什么python字典占用这么多内存?

Python gpt-2-simple,一次加载多个模型

python - 如何将字符串的所有排列作为字符串列表(而不是元组列表)?

python - 导入错误 : No module named 'yaml'

python - 是否可以使键盘模块与 pygame 和线程一起使用

python - 如何用py2exe更正TCL_LIBRARY和TK_LIBRARY

python - 对除 pandas 中的一列以外的所有列应用标准化

Python3字典基于值的合并

python - 如何将 python 字典的键显示为 HTML 表头,并将每个键的值显示为该表头下的一行?

python - Django migrate error _mysql_exceptions.ProgrammingError : (1064, "你的SQL语法有错误