【问题标题】:split the digits/ show the summation拆分数字/显示总和
【发布时间】: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

【问题讨论】:

    标签: split sum add digits


    【解决方案1】:

    要将数字的总和打印为表达式(如 4+5),您需要使用给定字符串的数字构建一个字符串。要打印以指定格式显示的字母,您需要将它们存储在一个列表中。

    def sum_of_digits(string):
    
        sum_digits = ""
        extracted_alphas = []
        
        if (len(string)==0):
            sum_digits = "" 
            print("Empty string entered!")     
            return 0
    
        for char in string:
            if char.isdigit() == True:
                sum_digits += char+"+"
        
            elif char.isalpha():
                extracted_alphas.append(char)
    
        if len(sum_digits) == 0:
            print("The sum of digits operation could not detect a digit!")
            print("The returned input letters are: ", extracted_alphas)
            return 0
        
        sum_digits = sum_digits[:-1]
        print("The sum of digits is", sum_digits,".")
        print("The extracted non-digits are: ", extracted_alphas)
        return sum_digits
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多