[英]Python Sum of digits in a string function
My function needs to take in a sentence and return the sum of the numbers inside. 我的函数需要接受一个句子并返回内部数字的总和。 Any advice?
有什么建议吗?
def sumOfDigits(sentence):
sumof=0
for x in sentence:
if sentence.isdigit(x)== True:
sumof+=int(x)
return sumof
Replace this: 替换为:
if sentence.isdigit(x)== True:
to: 至:
if x.isdigit():
examples: 例子:
>>> "1".isdigit()
True
>>> "a".isdigit()
False
your code should be like: 您的代码应类似于:
def sumOfDigits(sentence):
sumof=0
for x in sentence:
if x.isdigit():
sumof+=int(x)
return sumof
Some pythonic ways: 一些Python方式:
Using List Comprehension: 使用列表推导:
>>> def sumof(sentence):
... return sum(int(x) for x in sentence if x.isdigit())
...
>>> sumof("hello123wor6ld")
12
Using Filter, map: 使用过滤器,映射:
>>> def sumof(sentence):
... return sum(map(int, filter(str.isdigit, sentence)))
...
>>> sumof("hello123wor6ld")
12
Using Regular expression, extraction all digit: 使用正则表达式提取所有数字:
>>> import re
>>> def sumof(sentence):
... return sum(map(int, re.findall("\d",sentence)))
...
>>> sumof("hello123wor6ld")
12
You have to ask if x is a digit. 您必须询问x是否为数字。
def sumOfDigits(sentence):
sumof=0
for x in sentence:
if x.isdigit()== True:
sumof+=int(x)
return sumof
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.