【问题标题】:How to switch \n to a newline in list? [closed]如何将 \n 切换到列表中的换行符? [关闭]
【发布时间】:2019-03-05 16:30:41
【问题描述】:
    with open("C:\\test\\data1.txt") as f:
    data = f.readlines()
    tail = data[-10:]

我在文件夹 test 中有一个文件名 data1.txt,当我的程序从文件中读取时,它会从文件中读取全部内容并仅打印文件中的最后 10 行。

['这是行号 21\n', '这是行号 22\n', '这是行 number 23\n', '这是行号 24\n', '这是行号 25\n', '这是行号 26\n', '这是行号 27\n', '这是行 number 28\n', '这是第 29 行\n', '这是第 30 行\n']

我想用换行符打印文件的最后 10 行,但不知道如何在列表数据结构内的换行符内放置。

例如: 像这样打印txt文件(data1.txt):

这是第 21 行

这是第 22 行

这是第 23 行

这是第 24 行

没有\n和列表减速([''])

【问题讨论】:

  • 我不明白这个问题,你能添加一个你期望的具体例子吗?
  • 感谢您的评论,我希望每一行都单独示例:这是第 21 行和新行,这是第 22 行,依此类推...制作 /n一个效果,而不是一个普通的字符串
  • 添加示例到您的问题而不是评论。

标签: python python-3.x


【解决方案1】:

已经有很多答案了,但是没有人解释这个问题。

问题

\n 换行符!

说明

为了能够在字符串文字中显示换行符,使用了转义序列\n,例如:

>>> 'a\nb'
'a\nb'

>>> print('a\nb')
a
b

print 函数打印字符串,如果传递了字符串参数,但如果传递了其他对象,则首先必须将其转换为字符串,因此print(x) 与@987654327 相同@。

list 的字符串转换为字符串时,可以通过对其每个项目调用 repr 来完成:

>>> ['a', 'a\nb']
['a', 'a\nb']

>>> str(['a', 'a\nb'])
"['a', 'a\\nb']"

>>> print("['a', 'a\\nb']")
['a', 'a\nb']

解决方案

现在,如果你想打印最后 10 行,这意味着你应该打印列表中的每个字符串,而不是列表对象本身,例如:

for s in list_of_strings:
    print(s)

现在,由于 s 已经包含换行符并且print 本身添加了换行符,因此您应该删除其中一个换行符以使解决方案完整:

for s in list_of_strings:
    print(s.strip('\n'))

或:

for s in list_of_strings:
    print(s, end='')

或通过连接列表项创建一个字符串并打印:

print(''.join(list_of_strings))

【讨论】:

  • 感谢您的完整解释.. 太好了!
【解决方案2】:

最好是加入(适用于任何版本):

print(''.join(tail))

【讨论】:

    【解决方案3】:

    print这样的尾巴:

    print(*tail, sep='')
    

    sep 参数停止通常用作打印项目之间分隔符的自动空格。

    【讨论】:

    • Amm..,应该说在 python 2 上不起作用...
    • @U9-Forward 你可以在Python 2.6+中使用print函数,你只需要从脚本顶部的__future__ import print_function未来模块不应在其他导入之后导入)。
    • 感谢您的回复
    • @PM2Ring 正确,我的错,我的错误 :-)
    【解决方案4】:

    也许这会有所帮助:

    f.readlines()[-10:]
    

    这样你会得到最后 10 行。

    或者只是:

    data = f.readlines()[-10:]
    for d in data:
       print(d) # will print everything on new line
    

    【讨论】:

    • 安姆...,[-10:]...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2023-03-31
    • 2019-02-05
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多