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:
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.
def sumOfDigits(sentence):
sumof=0
for x in sentence:
if x.isdigit()== True:
sumof+=int(x)
return sumof
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.