计算文本中的空格数(将连续空格视为一个)

Zor*_*duk 4 python spaces python-3.x

如何以连续空格仅计为 1 的方式来计算文本中空格或换行符的数量?例如,这非常接近我想要的:

string = "This is an  example text.\n   But would be good if it worked."
counter = 0
for i in string:
    if i == ' ' or i == '\n':
        counter += 1
print(counter)
Run Code Online (Sandbox Code Playgroud)

15但是,结果不应返回为,而应仅为11

th3*_*aly 5

假设您被允许使用 Python 正则表达式;

import re
print len(re.findall(ur"[ \n]+", string))
Run Code Online (Sandbox Code Playgroud)

快捷方便!

更新:此外,使用[\s]而不是[ \n]匹配任何空白字符。