【发布时间】:2022-01-15 11:47:54
【问题描述】:
到目前为止,这是我的代码,但是当我运行 sum_of_digits("45ggd") 时,我得到以下结果:
数字的总和是9。
提取的非数字为:['ggd']
9
如我所愿:
数字的总和是 4 + 5。
提取的非数字为:['g', 'g', 'd']
9
def sum_of_digits(string):
sum_digits = 0
extracted_alphas = ""
for char in string:
if char.isdigit() == True:
sum_digits += int(char)
elif char.isalpha():
extracted_alphas += char
else:
if (len(string)==0):
sum_digits = ""
print("Empty string entered!")
return 0
elif char.isdigit() == False:
print("The sum of digits operation could not detect a digit!")
print("The returned input letters are: ['" + str(extracted_alphas) + "']")
return 0
print("The sum of digits is", sum_digits,".")
print("The extracted non-digits are: ['" + str(extracted_alphas) + "']")
return sum_digits
【问题讨论】: