Python sum digits in string

How to sum the digits in a string in Python

How to sum the digits in a string in Python. That’s the topic I want to introduce to you today. I would sum the digits on a string containing digits and non-digits, and the string consists of only digits. If you’re curious about this topic, read it all.

Sum the digits in a string in Python

String containing digits and non-digits.

Use the str.isdigit() function.

The str.isdigit() function returns True if the string contains only digits and False otherwise.

  • Declare a function that sums the digits in a string.
  • The for loop loops through that string. In each iteration, look up the digit using the str.isdigit() function. If it’s a digit, use the int() function to convert it back to an integer.
  • Finally, sum those integers.
def sumDigitsStr(strObj): sumDigit = 0 for i in strObj: if i.isdigit() == True: digits = int(i) sumDigit = sumDigit + digits return sumDigit print('The sum of the digits in the string is:', sumDigitsStr('12learnshareit34'))
The sum of the digits in the string is: 10

With the same idea, you can use list comprehension to make everything faster.

testStr = '12learnshareit34' # Use the list comprehension to the sum of digits sumDigits = sum(int(i) for i in testStr if i.isdigit()) print('The sum of the digits in the string is:', sumDigits)
The sum of the digits in the string is: 10

Use the str.isnumeric() function.

The function str.isnumeric() and the function str.isdigit() are pretty similar in effect, so the idea of ​​using the str.isnumeric() function is similar to using the str.isdigit() function.

  • Declare a function that sums the digits in a string.
  • The for loop loops through that string. In each iteration, look up the digit using the str.isnumeric() function. If it’s a digit, use the int() function to convert it back to an integer.
  • Finally, sum those integers.
def sumDigitsStr(strObj): sumDigit = 0 for i in strObj: if i.isnumeric() == True: digits = int(i) sumDigit = sumDigit + digits return sumDigit print('The sum of the digits in the string is:', sumDigitsStr('12learnshareit34'))
The sum of the digits in the string is: 10

You can also use list comprehension to do the sum of digits in this way.

testStr = '12learnshareit34' # Use the list comprehension to the sum of digits sumDigits = sum(int(i) for i in testStr if i.isnumeric()) print('The sum of the digits in the string is:', sumDigits)
The sum of the digits in the string is: 10

The string consists of only digits.

For strings containing only digits, you won’t have to use the str.isdigit() function and the str.numeric() function to check.

testStr = '1234' # Use the list comprehension to the sum of digits sumDigits = sum(int(i) for i in testStr) print('The sum of the digits in the string is:', sumDigits)
The sum of the digits in the string is: 10

Summary:

In conclude, this article have shown you the causes with several ways to sum the digits in a string in Python. If you have any suggestions or comments about the article, please comment.

Читайте также:  Creating classes and objects in java

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

Sum of all digits in a string

Below is my solution for the problem above. I feel like this can be turned into one line. I would really only like suggestions on the actual algorithm, but anything else is appreciated.

def sum_numbers(string: str) -> int: """ Returns the sum of all the numbers in the string """ num_sum = 0 for char in string: if char.isnumeric(): num_sum += int(char) return num_sum if __name__ == '__main__': # Test Cases # assert sum_numbers("123") == 6 assert sum_numbers("abc") == 0 assert sum_numbers("4x7") == 11 assert sum_numbers("wefbyug87iqu") == 15 assert sum_numbers("123456789") == 45 

\$\begingroup\$ I feel like a better title would be «Sum of all digits in a string.» Digits imply «abc10def10» is 2, numbers implies 20. \$\endgroup\$

2 Answers 2

You’re right, it can be turned into one line using comprehension syntax which would be your best option of you’re looking for a slightly more efficient code.

  • isdecimal() is better to use in this case than isnumeric() because the isnumeric() accepts types like ½ and ¼ and n² which might produce some side effects you don’t want if you’re using this function for some real application. Apart from this the code looks good, can be improved using the comprehension syntax which is more efficient and shorter.

Improved version:

def sum_digits(chars: str) -> int: """Return sum of numbers in chars""" return sum(int(char) for char in chars if char.isdecimal()) if __name__ == '__main__': print(sum_digits('abcd173fg')) print(sum_digits('abcd')) print(sum_digits('173678')) 

\$\begingroup\$ @AJNeufeld is it necessary to write functions in this form def func(x: some_type) -> another_type: ? \$\endgroup\$

\$\begingroup\$ @brijeshkalkani what solution do you expect from the string ‘2.53.6’? It is not a valid float. There are several ways it could be interpreted: 2 + 5 + 3 + 6 = 16; 2.5 + 3.6 = 6.1; 2 + 53 + 6 = 61; 2.53 + 6 = 8.53 \$\endgroup\$

\$\begingroup\$ @IEatBagels Did you post your comment on the wrong answer? This answer only iterates through the string once. The answer by c4llmeco4ch iterates through the string multiple times. \$\endgroup\$

\$\begingroup\$ @IEatBagels to clarify AJNeufeld’s comment, this code is using a generator expression instead of a list comprehension, so the code does not iterate through the string multiple times. \$\endgroup\$

We could also do something like:

def sum_numbers(string: str) -> int: """Return sum of numbers in string""" return sum([string.count(str(i)) * i for i in range(10)]) if __name__ == '__main__': print(sum_numbers('hel3l4o55')) #should print 17 print(sum_numbers('xdman')) #should print 0 print(sum_numbers('123456789')) #should print 45 

This differs from your implementation due to the fact that my loop iterates over the digits while yours loops through the string itself. This means a few things:

  1. If a string has at least one of every digit, this implementation skips out on checking for 0s.
  2. Depending on how Python internally runs the list.count function, there is a chance this implementation is wildly inefficient overall. I likely loop through the strings more times than its worth, so this becomes worse as the length of the string becomes sizeable enough.

Ultimately, this is just a different idea on what we can loop around. As the number of things we need to search for (and in turn, the number of things we have to run a count on increases), the more times we search through the string, wasting time. However, if we are only looking for one thing or a small sample of possible results, list.count is a good option to have available.

EDIT: might also depend on how floats are looked at as mentioned in the above comments. If they are supposed to just be read as individual chars then this works fine. If you’re expected to parse whole sections to determine what is and isn’t a float/multi-char number, this falls apart.

Источник

Python program to find the sum of digits in a string

This tutorial will show you how to find the sum of digits in a string. We will learn different ways to solve this problem. The program will read one string as user input and it will calculate the sum of all digits in that string.

To solve this problem, we will iterate through the characters of the string one by one. Using isdigit() method, we can check if one character is digit or not. If it is a digit, we will add its value to a different sum variable that holds the total sum of all digits.

Let’s try to do this by using a for loop. This loop will iterate through the characters of the string one by one and if it find any digit, it will add it to the final sum.

Let’s take a look at the below program:

def sum_digits(str): sum = 0 for c in str: if c.isdigit() == True: sum += int(c) return sum given_str = input("Enter a string : ") print(sum_digits(given_str))

In this program, we have defined one function sum_digits to find the sum of all digits of a string. It takes one string as parameter and returns the sum of all numbers found in the string.

We are using one for loop to find if a character is digit or not using isdigit() method. If it returns True, we are adding the integer value of that character to sum.

: hello123 6 Enter a string : hello123 world45 15

We can also write the same program in one line.

def sum_digits(str): return sum(int(c) for c in str if c.isdigit()) given_str = input("Enter a string : ") print(sum_digits(given_str))

We are doing the same thing in this program but in one line. If you run this program, it will print the same output.

Источник

Python: Compute sum of digits of a given string

Write a Python program to compute the sum of the digits in a given string.

Sample Solution:-

Python Code:

def sum_digits_string(str1): sum_digit = 0 for x in str1: if x.isdigit() == True: z = int(x) sum_digit = sum_digit + z return sum_digit print(sum_digits_string("123abcd45")) print(sum_digits_string("abcd1234")) 

Pictorial Presentation:

Flowchart: Compute sum of digits of a given string

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Converting string into datetime:

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

  • Python documentation for strptime: Python 2, Python 3
  • Python documentation for strptime/strftime format strings: Python 2, Python 3
  • strftime.org is also a really nice reference for strftime
  • strptime = «string parse time»
  • strftime = «string format time»
  • Pronounce it out loud today & you won’t have to search for it again in 6 months.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью