如何计算字符串中不同字符的数量,即字符串 str("true") 中有多少个“t、r、u、e”字符

问题描述 投票:0回答:1

尝试计算单词 true 中某些字母的数量,有什么更简单的方法可以做到这一点?

我希望有一个更简单的解决方案,可以给我 4 作为答案!

python string count counter
1个回答
0
投票

您可以使用集合,但确切的方法取决于确切的预期逻辑。

target = {'t', 'r', 'u', 'e'}

### counting each unique letter that is also in target

word = 'true'

len(set(word) & target)
# 4

word = 'test'    # t and e are counted (once), not s

len(set(word) & target)
# 2


### counting all letters
# here t, e, t are counted, not s

sum(1 for c in word if c in target)
# 3
© www.soinside.com 2019 - 2024. All rights reserved.