Python processing strings: Adding numbers in a string to sum

Source: Internet
Author: User

Computes the and of all numbers in a string, with a combination of numbers and letters
If consecutive numbers appear, follow one number
The specific explanation is in the line of code:
defsum_str (str1): Len1=len (STR1)#first assign the length of the string str1 to Len1sum = N = 0#create an empty variable with a value of 0 sun #建立一个值为0的空变量n     forIinchRange (LEN1):#use I to traverse the length of a string        if<= Ord (Str1[i]) <= 57:#determines whether the ASCII code of a character is within the range of the digital ASCII valuen = n * 10#N *=n = Int (str1[i]) + N#n + = Int (str1[i])        Else: Sum= n + sum#sum + = nn =0#the above 6 lines of code means starting with the 0 subscript, traversing the string, if it is a number, using n plus its number,        #The execution logic is, meet a number, with N Plus, if the next or the number, the previous number by 10 plus this number, sequentially loop        #For example: continuous digital DF123ASD = ((1*10+2) *10) +3        #if it is not a number, add the n value to the variable sum, save it, and re-assign N to 0 to enter the For loop again (Sun only appears when it meets the letter, collecting the value of the number before the number)        #next time you hit the number (meet if condition), the logic below the loop (if) conditionsum = n +sumPrint(sum) str1="b532x2x3c4b5"sum_str (str1) #调用函数

Operation Result:

Python processing strings: Adding numbers in a string to sum

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.