You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现统计输入字符串中以‘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 integer count to accumulate matches—this is more efficient for a counting task.
  • Infinite Loop with Break: while True runs indefinitely until we hit the empty string condition (s == ""), which triggers a break to exit the loop.
  • startswith() Method: Python's built-in str.startswith(substring) is perfect here—it returns True if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:02:33