Python extracts numbers in a string

Source: Internet
Author: User

Title: "This is a simplification of a complex problem" here is a list of strings, extracting the second number in the string, and judging if it is greater than 1000, and if so, remove the line from the list.

1000\t1002\n

... "omitted" ....

Code:

<pre name= "code" class= "python" >oldstr = "1000\t1002\n" NEWSTR = oldstr# match target digit left string t=newstr.index ("\ t") Newstr = Newstr.lstrip (newstr[0:t]) Newstr = Newstr.lstrip ("\ t") Newstr = Newstr.rstrip ("\ n") if int (newstr) >1000:print ' Ok ' else:print ' sorry '
#结果: OK

You can then continue with the subsequent delete operation.

Easy Error 1: After the string is strip (), the string content remains unchanged if no value is assigned.

>>> Newstr.lstrip ("\ t") ' 1002\n ' >>> newstr.rstrip ("\ n") ' \t1002 '

One more example:

>>> ss= "124" >>> ss[0] ' 1 ' >>> Ss.lstrip (ss[0]) ' [1 ' >>> ss[0] #ss [0] remain the same as ' >> ' ' > Ss=ss.lstrip (ss[0]) # assignment SS get new value >>> SS ' >>> ss[0] #ss [0] change ' 2 '

Easy Error 2: If NEWSTR[0:T] is changed to newstr[0:t+1], you cannot get 1002, but 002. Cause unknown origin.


Copyright NOTICE: Welcome reprint, Reprint please indicate the source http://blog.csdn.net/ztf312/

Python extracts numbers in a string

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.