- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find sum of digits that are inside one alphanumeric string in Python
Suppose we have an alphanumeric string s with digits from "0" to "9" and lowercase English letters. We have to find the sum of the numbers that are present in s. If digits are consecutive then consider them into a single number.
So, if the input is like s = "hello25world63power86", then the output will be 174 because 25+63+86 = 174
To solve this, we will follow these steps −
ret := 0, curr := 0
for each ch in s, do
if ch is a digit, then
curr := 10 * curr + (ch as an integer)
otherwise,
ret := ret + curr
curr := 0
return ret + curr
Example
Let us see the following implementation to get better understanding
from string import digits def solve(s): ret = 0 curr = 0 for ch in s: if ch in digits: curr = 10 * curr + int(ch) else: ret += curr curr = 0 return ret + curr s = "hello25world63power86" print(solve(s))
Input
"hello25world63power86"
Output
174
- Related Articles
- Program to find minimum digits sum of deleted digits in Python
- Program to find sum of digits until it is one digit number in Python
- Program to find sum of digits in base K using Python
- Program to find whether a string is alphanumeric.
- Program to find number of subsequence that are present inside word list in python
- Python Program to accept string ending with alphanumeric character
- Program to find the sum of all digits of given number in Python
- Python Program to Find the Sum of Digits in a Number without Recursion
- Alphanumeric Abbreviations of a String in C Program?
- Java regex program to verify whether a String contains at least one alphanumeric character.
- Python - Check If All the Characters in a String Are Alphanumeric?
- 8086 program to find sum of digits of 8 bit number
- 8085 program to find sum of digits of 8 bit number
- Python program to find the sum of all even and odd digits of an integer list
- Program to find nearest number of n where all digits are odd in python

Advertisements