-1

I am new to coding and try to extract and print the none digits. I've written 2 different codes but cannot combine them. I would appreciate some advices. (i tried using *args but didn't work)

def SumOfDigits(str1):
    sum_digit = 0
    for x in str1:
        if x.isdigit():
            z = int(x)
            sum_digit += z
    print("The sum of digits operation is", sum_digit, end=".")
    return   
def SumOfDigits(input):
    valids = []
    for character in input:
        if character.isalpha():
            valids.append(character)
    print("The extracted non-digits are:", ''.join(valids))
    return
wjandrea
  • 28,235
  • 9
  • 60
  • 81
El. Nik
  • 11
  • 1
  • Welcome to Stack Overflow! Please take the [tour] and read [ask]. What's your question? Please [edit] to clarify. If you're looking for debugging help, you need to make a [mre] including complete but minimal code (to start, the call to `SumOfDigits()`), example input, expected output, and actual output--or if you get an error, the [full error message with traceback](https://meta.stackoverflow.com/q/359146/4518341). – wjandrea Dec 07 '21 at 20:41
  • What do you mean by "none digits"? Is that a typo of "non-digits"? – wjandrea Dec 07 '21 at 20:43
  • Suggestion: `sum_digit` can be calculated with a generator expression and `sum` quite nicely. `sum(int(x) for x in str1 if x.isdigit())` – Chris Dec 07 '21 at 20:44

1 Answers1

0

El. Nik, i believe that those 2 function you not be merged as they are doing different behavior, which lead to a more complex function, that might get a bit confusing.

Anyway, what you want is to merge your two for loop into a single one. Since str.isalpha matches do not collide with str.isdigit ones, you can safely use a if statement followed by an elif to check every charater and apply the wanted behavior.

Then, you simply return the 2 results as a tuple.

def digit_extraction(string):
    sum_digits = 0
    extracted_alphas = ""

    for char in string:
        if char.isdigit():
            sum_digits += int(char)

        elif char.isalpha():
            extracted_alphas += char

    return sum_digits, extracted_alphas

Here is a quick example:

>>> digit_extraction("1a2b3c4d5e6f7g8h9i")
(45, 'abcdefghi')

If you dont know how multiple return value works in python, i'd suggest to check the following tutorial:

https://datagy.io/python-return-multiple-values/

To get into something more advanced, separating the 2 function would allow for writting something considered as more pythonic:


def sum_of_digits(string):
    return sum(int(c) for c in string if c.isalpha())

and

def extract_alphas(string):
    return ''.join(filter(str.isalpha, c))
Yohann Boniface
  • 494
  • 3
  • 10