我应该如何计算字符串中数字的个数?
例如:
>>> count_digits("ABC123")
应该返回3。
试试这个:
len("ABC123")
非常简单。你可能需要阅读有关len
的文档。
编辑 你最初的帖子不明确,无法确定你是想要总长度还是数字个数。既然你想要后者,我应该告诉你有很多种方法可以做到这一点,以下是其中三种:
s = "abc123"
print len([c for c in s if c.isdigit()])
print [c.isdigit() for c in s].count(True)
print sum(c.isdigit() for c in s) # I'd say this would be the best approach
count(True)
,而是对列表求和:sum(c.isdigit() for c in s)
。 - Ashwini Chaudharys = 'ABC123'
len([c for c in s if c.isdigit()]) ## 3
或者你想计算相邻数字的数量。
s = 'ABC123DEF456'
import re
len(re.findall('[\d]+', s)) ## 2
sum(1 for c in "ABC123" if c.isdigit())
sum(c.isdigit() for c in "ABC123")
的意思是统计字符串 "ABC123" 中数字字符的数量。 - Ashwini Chaudhary
.translate()
解决方案的人...我一开始认为那很疯狂,但事实证明它比其他任何已发布的解决方案都快上一个数量级。真是个惊喜。 - Rob Cowie