2

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

'          hi there'

我想得到数字“10”,因为它是该字符串中最长的“连续”空格,而不是“11”,它是所有空格的数量。

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

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

'hkhkh

 hk           hk`

在一个输入中大约有 5 条不同的线路。

4

2 回答 2

4

你会想看看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)
于 2012-09-20T02:46:06.720 回答
0

您将什么定义为空白。仅空格或也:tab ( \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

于 2012-09-20T16:03:48.147 回答