如何实现统计输入字符串中以‘foo’开头的数量及空输入终止逻辑?
Solution to Count Strings Starting with 'foo'
Got it, let's wrap up your code to get the job done! Here's the complete implementation that counts how many input strings start with foo until you enter an empty string:
# Initialize a counter to keep track of matching strings count = 0 # Loop until empty string is entered while True: print("please enter string: ", end="") s = input() # Exit loop if input is empty if s == "": break # Check if the string starts with 'foo' and increment counter if yes if s.startswith('foo'): count += 1 # Output the final count print(f"Number of strings starting with 'foo': {count}")
Key Details Explained:
- Counter Variable: Instead of a list (
answer), we use a simple integercountto accumulate matches—this is more efficient for a counting task. - Infinite Loop with Break:
while Trueruns indefinitely until we hit the empty string condition (s == ""), which triggers abreakto exit the loop. startswith()Method: Python's built-instr.startswith(substring)is perfect here—it returnsTrueif the string begins with the specified substring, making our check clean and readable.
Test with Your Example:
If you input:
foohi
nothingfoo
fooboo
(press enter without typing anything)
The output will be Number of strings starting with 'foo': 2, which matches your expected result.
内容的提问来源于stack exchange,提问作者thor
相关产品推荐
相关产品推荐

