如何用Python统计字符串中"dance"的出现次数(排除"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

