我要找出輸入中連續的空白字符數。比方說,如果輸入的是:要在輸入中找到連續的空白字符
' hi there'
我想要得到的數字「10」,因爲這是在該字符串,而不是「11」,這是所有空間的數量最長的「連續」的空間。
任何形式的幫助最受讚賞。
謝謝!我明白如何爲一個字符串做到這一點,但輸入應該是多行,我似乎無法與它一起工作。輸入是這樣的:
'hkhkh
hk hk`
在一個輸入中有大約5個不同的行。
我要找出輸入中連續的空白字符數。比方說,如果輸入的是:要在輸入中找到連續的空白字符
' hi there'
我想要得到的數字「10」,因爲這是在該字符串,而不是「11」,這是所有空間的數量最長的「連續」的空間。
任何形式的幫助最受讚賞。
謝謝!我明白如何爲一個字符串做到這一點,但輸入應該是多行,我似乎無法與它一起工作。輸入是這樣的:
'hkhkh
hk hk`
在一個輸入中有大約5個不同的行。
你會想看看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)
你怎麼定義爲空白。只是空間或也: 標籤(\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? '"/%[email protected]#$ 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
如果你想把選項卡考慮進去。
不錯。你認爲如何替換for循環: max_len = max(len(list(subgroup))for substring,subgroup in groupby(split_string)if substring =='')' –
@WarrenWeckesser - 完全合法,但對於初學者來說難度很大:-) –