【问题标题】:How can I get the total number of characters in the given string that are digits? [closed]如何获取给定字符串中的数字字符总数? [关闭]
【发布时间】:2015-03-20 21:18:56
【问题描述】:

如何计算字符串的位数?

例如:

>>> count_digits("ABC123")

应该返回 3。

【问题讨论】:

  • user1718467,基于您对@A 的评论。 R.S. 我已经修改了你的问题。如果您不同意,请在 cmets 中告诉我
  • 说真的,您不能在 Google 中输入相同的内容吗?
  • 致发布然后删除使用.translate() 的解决方案的人...我认为这很疯狂,但事实证明它比发布的任何其他解决方案都要快一个数量级。一个真正的惊喜。
  • @RobCowie 问题是,它的工作方式错误,它剥夺了数字,这就是我再次删除它的原因。
  • 这个问题没有太本地化。

标签: python string


【解决方案1】:

试试这个:

len("ABC123")

简单得像馅饼。您可能有必要阅读有关lendocumentation


编辑您的原始帖子在您想要总长度还是位数方面模棱两可。看到你想要后者,我应该告诉你,有一百万种方法可以做到,这里有三种:

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)
  • @AshwiniChaudhary 是的,只是想表明有多种方法可以解决它 - 但你是对的。
【解决方案2】:

我怀疑你想计算字符串中的位数

s = 'ABC123'
len([c for c in s if c.isdigit()]) ## 3

或者你可能想计算相邻数字的个数

s = 'ABC123DEF456'
import re
len(re.findall('[\d]+', s)) ## 2

【讨论】:

  • 感谢正则表达式解决方案!例如,它更强大,可以扩展到识别货币。
【解决方案3】:
sum(1 for c in "ABC123" if c.isdigit())

【讨论】:

  • 或者干脆sum(c.isdigit() for c in "ABC123")`
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
相关资源
最近更新 更多