【发布时间】: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') -
太棒了,非常感谢大家!