我需要计算一行中的字符数。 我尝试了各种方法,但它们都提供了不正确的输出。
我试过了:
with file as f:
for line in file:
chars = len(line)
但输出结果却是200美元。
我最终这样做了:
with file as f:
for line in f:
self.length += 1
self.count = len(list(line.strip('\n')))
这返回了行数和最后一行中的字符数。
编辑:我不知道为什么我因为提出一个明显遵守所有规则的问题而被投票。答案 0 :(得分:1)
我假设您正在从文本文件中读取行。
为什么不使用.splitlines()或.strip()将每一行附加到列表中?然后你可以在每个列表元素上使用len()函数。
*编辑:措辞
答案 1 :(得分:0)
如果您想获得每一行的长度,而不仅仅是最后一行,请使用以下代码:
with open('file.txt') as myfile:
for line in file:
print len(line)
file.txt
Hello there,
What is your name?
Bye
13
1
19
1
4
>>> with open('file.txt') as myfile:
... for line in myfile:
... print len(line)
...
13
1
19
1
4
>>>
如果你想知道为什么一个看似epty的行长度为1,那是因为换行符在python中保存为'\n'
。实际文件如下:
>>> myfile = open('file.txt').read()
>>> myfile
'Hello there,\n\nWhat is your name?\n\nBye\n'
>>>
但是当你调用print
时,它会将转义序列转换为新行:
>>> myfile = open('file.txt').read()
>>> print myfile
Hello there,
What is your name?
Bye
>>>