【问题标题】:Want to remove \n from len [duplicate]想要从 len 中删除 \n [重复]
【发布时间】:2022-01-14 20:00:20
【问题描述】:

这是我的任务:

为您提供了一个 books.txt 文件,其中包括书名,每一个都写在单独的行上。 逐一阅读标题,并将每本书的代码分别输出到一行。

例如,如果 books.txt 文件包含:

Some book
Another book

你的程序应该输出:

S9
A12
file = open("/usercode/files/books.txt", "r")

with file as f:
    lines = f.readlines()
    for i in lines:
        count = len(i)
        count = str(count - 1)
        print(i[0]+count)
    

file.close()

这会输出所有正确的内容,但最后一行是因为 i[#lastLine] 是在最后一次计数之后完成的,如果这有意义吗?(我正在学习可能完全错误)

基本上我想知道我的代码哪里出错了。我相信这是我构造 for i in lines 部分的方式,应该以不同的方式处理 \n

count = len(i) count = str(count - 1)

回答

感谢您通知我,添加 i = i.strip() 会删除新行,也就是 \n 来解决问题!

工作代码:

file = open("/usercode/files/books.txt", "r")

with file as f:
    lines = f.readlines()
    for i in lines:
        i = i.strip('\n') #Strips new lines aka \n
        count = str(len(i))
        print(i[0]+count)
    

file.close()

【问题讨论】:

  • 如何在我的代码中使用它我还没有学过。会不会像 line.strip('\n')
  • 默认情况下,.strip() 去除新行
  • i = i.strip() 作为for 循环的第一行。默认情况下,它会删除字符串开头和结尾的所有空格,包括换行符。如果您只想删除换行符,请使用i.strip('\n')
  • 太棒了,非常感谢大家!

标签: python list output


【解决方案1】:

您可以在 i 上使用 strip() 删除新行。

strip - 返回删除了前导和尾随字符的字符串副本。 Python docs strip

您可以将您的计数作为 str() 进行打印。

str() 返回一个包含对象可打印表示的字符串。

Python docs str 正如 cmets 指出的那样,建议还将 i 更改为 line 以提高可读性。

file = open("books.txt", "r")

with file as f:
    lines = f.readlines()
    for line in lines:
        count = str(len(line.strip()))
        print(line[0]+count)
    

file.close()

【讨论】:

  • 另外,格式化字符串会让这个更干净。 print(f"{line[0]}{len(line.strip()) - 1}")
  • 谢谢你,我确实需要清理我的代码
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2021-03-04
  • 2014-10-09
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多