Python 3.x - 不要用 len 计算回车 returns
Python 3.x - don't count carriage returns with len
我正在编写以下代码作为练习的一部分:
input_file = open('/home/me/01vshort.txt', 'r')
file_content = input_file.read()
input_file.close()
file_length_question = input("Count all characters (y/n)? ")
if file_length_question in ('y', 'Y', 'yes', 'Yes', 'YES'):
print("\n")
print(file_content, ("\n"), len(file_content) - file_content.count(" "))
它在输出中计算回车 returns,因此对于以下文件 (01vshort.txt),我得到以下终端输出:
Count all characters (y/n)? y
0
0 0
1 1 1
9
...或者...
Count all characters (y/n)? y
0
00
111
9
在这两种情况下,答案应该是 6,因为有 6 个字符,但我得到的结果是 9。
我已确保代码省略了空格,并通过故意添加空格和 运行 带有和不带有以下行的代码对我的输入文件进行了测试:
- file_content.count(" ")
任何人都可以帮助解释为什么结果是 9 而不是 6 吗?
也许根本就不是马车returns?
我也很好奇为什么9的结果缩进1个空格?输入文件仅包含以下内容(文件末尾有一个空行,示例中指示的行号):
1. 0
2. 0 0
3. 1 1 1
4.
...或者...
1. 0
2. 00
3. 111
4.
谢谢。
你得到的是 9,因为文件的内容可以解释为:
file_content = "0\n0 0\n1 1 1\n"
并且您只匹配白色 spaces (file_content.count(" ")
)。
为了只计算字符数,您可以:
- 逐行读取文件,或者
- 使用正则表达式匹配白色 space。
对于 9
的缩进:print
处理逗号 as outlined here
如果您想忽略所有白色space 字符,包括制表符和换行符以及其他控制字符:
print(sum(not c.isspace() for c in file_content))
会给你 6
你期望的。
或者,您可以利用不带参数的 .split()
方法将在任何白色 space 字符上拆分字符串这一事实。所以将它分成非 space 块,然后在没有白色 space 字符的情况下再次将它们重新组合在一起:
print(len(''.join(file_content.split())))
我正在编写以下代码作为练习的一部分:
input_file = open('/home/me/01vshort.txt', 'r')
file_content = input_file.read()
input_file.close()
file_length_question = input("Count all characters (y/n)? ")
if file_length_question in ('y', 'Y', 'yes', 'Yes', 'YES'):
print("\n")
print(file_content, ("\n"), len(file_content) - file_content.count(" "))
它在输出中计算回车 returns,因此对于以下文件 (01vshort.txt),我得到以下终端输出:
Count all characters (y/n)? y
0
0 0
1 1 1
9
...或者...
Count all characters (y/n)? y
0
00
111
9
在这两种情况下,答案应该是 6,因为有 6 个字符,但我得到的结果是 9。
我已确保代码省略了空格,并通过故意添加空格和 运行 带有和不带有以下行的代码对我的输入文件进行了测试:
- file_content.count(" ")
任何人都可以帮助解释为什么结果是 9 而不是 6 吗?
也许根本就不是马车returns?
我也很好奇为什么9的结果缩进1个空格?输入文件仅包含以下内容(文件末尾有一个空行,示例中指示的行号):
1. 0
2. 0 0
3. 1 1 1
4.
...或者...
1. 0
2. 00
3. 111
4.
谢谢。
你得到的是 9,因为文件的内容可以解释为:
file_content = "0\n0 0\n1 1 1\n"
并且您只匹配白色 spaces (file_content.count(" ")
)。
为了只计算字符数,您可以:
- 逐行读取文件,或者
- 使用正则表达式匹配白色 space。
对于 9
的缩进:print
处理逗号 as outlined here
如果您想忽略所有白色space 字符,包括制表符和换行符以及其他控制字符:
print(sum(not c.isspace() for c in file_content))
会给你 6
你期望的。
或者,您可以利用不带参数的 .split()
方法将在任何白色 space 字符上拆分字符串这一事实。所以将它分成非 space 块,然后在没有白色 space 字符的情况下再次将它们重新组合在一起:
print(len(''.join(file_content.split())))