Python 如何获取给定字符串中的数字字符总数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12717435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the total number of characters in the given string that are digits?
提问by user1718467
How do I count the number of digits in a string?
如何计算字符串中的位数?
For example:
例如:
>>> count_digits("ABC123")
should return 3.
应该返回 3。
回答by arshajii
Try this:
尝试这个:
len("ABC123")
Simple as pie. It might behoof you to read the documentationregarding len.
简单如馅饼。这可能自知之明您阅读文档有关len。
EditYour original post was ambiguous about whether you wanted the total length or the number of digits. Seeing as you want the latter, I should tell you that there are a million ways of doing it, here are three:
编辑您的原始帖子对于您想要总长度还是数字数量不明确。既然你想要后者,我应该告诉你,有一百万种方法可以做到,这里有三种:
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
回答by Rob Cowie
I suspect you want to count the number of digits in a string
我怀疑您想计算字符串中的位数
s = 'ABC123'
len([c for c in s if c.isdigit()]) ## 3
Or perhaps you want to count the number of adjacent digits
或者你想计算相邻数字的数量
s = 'ABC123DEF456'
import re
len(re.findall('[\d]+', s)) ## 2
回答by kindall
sum(1 for c in "ABC123" if c.isdigit())

