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

如何用Python统计字符串中"dance"的出现次数(排除"dances")

One-Line Solution to Count "dance" (Excluding "dances")

Great question! You can absolutely condense your logic into a single line of Python code—here are a couple of straightforward ways to do it:

Option 1: Combine Your Original Logic

Your initial approach is solid, and you can just merge the two count() calls into one expression without repeating code unnecessarily:

var = "Boys dance, girls dance, he dances, she dances"
count = var.count("dance") - var.count("dances")
print(count)  # Output: 2

If you really want to cram everything into one line (though readability should be a priority), you can even define the string and calculate the count in a single statement:

count = "Boys dance, girls dance, he dances, she dances".count("dance") - "Boys dance, girls dance, he dances, she dances".count("dances")

But the first version is cleaner—no need to duplicate the string.

Option 2: Use Regex for Exact Word Matching

If you want to ensure you only match the standalone word "dance" (and not accidentally catch it as part of longer words like "dances"), regular expressions are a great tool:

import re
count = len(re.findall(r'\bdance\b', "Boys dance, girls dance, he dances, she dances"))
print(count)  # Output: 2

The \b in the regex pattern stands for a word boundary, so it will only match "dance" when it's a complete word, not when it's followed by an 's' (or any other characters that make it part of a longer word).

Both methods will give you the correct count of 2 in a more concise way than your original multi-line code.


内容的提问来源于stack exchange,提问作者puregeek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:00:44