Вы можете использовать встроенную python split
, чтобы разбить строку на список слов, и метод startswith
, чтобы найти слова, начинающиеся с foo
.
def count_foo() -> int:
while True:
print("please enter string: ")
s = input().strip()
if s == "":
break
else:
# counter
answer = 0
# split the string to make a list of individual words
words = s.split()
# iterate through the list and find words
# that starts with foo
for word in words:
if word.startswith('foo'):
answer += 1
print(answer)
if __name__ == "__main__":
answer = count_foo()
* 1006. * Теперь, когда появится подсказка, добавьте вашу строку:
foohi nothingfoo fooboo example
Это выведет:
2
Если вы просто нажмете enter
, не вводя ничего в подсказку ввода, оно выйдет из л oop.