在输入中查找连续的空格字符

时间:2012-09-20 02:36:11

标签: python python-3.x spaces counting

我要找出输入中连续的空格数。假设输入是:

'          hi there'

我希望得到数字'10',因为那是该字符串中最长的'连续'空格而不是'11',这是所有空格的数量。

非常感谢任何形式的帮助。

谢谢!我现在知道如何为一个字符串做这个,但输入应该是多行,我似乎无法使用它。输入是这样的:

'hkhkh

 hk           hk`

在一个输入中有大约5个不同的行。

2 个答案:

答案 0 :(得分:3)

您需要查看itertools.groupby

from itertools import groupby

my_string = '          hi there'
current_max = 0

# First, break the string up into individual strings for each space
split_string = my_string.split(" ")

# Then, iterate over the list returning each string
# along with an iterator containing all the matches
# that follow it in a connected run
# e. g. "aaabbaa" would produce a data structure akin to this:
# [("a", ["a", "a", "a"]), ("b", ["b", "b"]), ("a", ["a", "a"])]
for c, sub_group in groupby(split_string):
    # If the string is not an empty string (e. g. it was not a space)
    # we are not interested in it - so skip this group.
    if c != '':
        continue

    # Get the length of the run of spaces
    i = len(list(sub_group))
    if i > current_max:
        current_max = i

print("The longest run of spaces is", current_max)

答案 1 :(得分:0)

你将什么定义为空白。只是空格或者: 标签(\t) 回车(\r) 换行符(\n

some_string = """hkhkh

 hk           hk



           and here"""

ls = longest_streak = 0
cs = current_streak = 0

for character in some_string:

    # or some other test will depend on your use case (numbers? '"/%$!@#$ etc.).
    # if not character in (' ', '\n', '\r', '\t'): 
    if character.isalpha():
        if cs > ls:
            ls = cs
        cs = 0
        continue

    elif character in ('\r', '\n'):
        continue

    else:
        cs += 1


print(ls)

elif如果遇到\r \n隐藏字符,则会继续显示当前条纹;如果您想要考虑标签,还可以添加\t