想从 len 中删除 \n

Want to remove \n from len

这是我的任务:

您获得了一个 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) 计数 = 海峡(计数 - 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()

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

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

您可以将计数转换为 str() 进行打印。

str() Returns 包含对象的可打印表示的字符串。

Python docs str 正如评论所指出的,建议也将 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()