あなたは見てみたいと思うでしょう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)