python calculates the sum and instance of all numbers in a string

  • 2021-06-28 12:59:53
  • OfStack

As follows:


#  Calculation 1 Sum of all numbers in string 
 
 
def numsum(s):
 
  sum = 0               # Define variables, prepare to record the sum of numbers 
 
  for i in range(len(s)):       # Traversal string 
 
    if s[i] >= '0' and s[i] <= '9':  # If i The character at is a numeric character 
 
      sum = sum + int(s[i])    # Convert Characters to int , sum 
 
  return sum
 
 
s = input(" Please enter 1 Strings :")
 
print(numsum(s))

Related articles: