My function needs to take in a sentence and return the sum of the numbers inside. Any advice?
def sumOfDigits(sentence):sumof=0for x in sentence:if sentence.isdigit(x)== True:sumof+=int(x)return sumof
My function needs to take in a sentence and return the sum of the numbers inside. Any advice?
def sumOfDigits(sentence):sumof=0for 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=0for x in sentence:if x.isdigit():sumof+=int(x)return sumof
Some pythonic ways:
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