[Tutor] count numbers only in the string

Prasad, Ramit ramit.prasad at jpmorgan.com
Tue Mar 6 21:42:43 CET 2012


> -----Original Message-----
> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-
> bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of kumar s
> Sent: Tuesday, March 06, 2012 2:08 PM
> To: tutor at python.org
> Subject: [Tutor] count numbers only in the string
> 
> Hi :
> 
> I have some strings with both alpha-numeric strings. I want to add all the
> numbers in that string and leave characters and special characters.
> 1A0G19
> 
> 5G0C25^C52
> 
> 0G2T3T91
> 44^C70
> 
> How can I count only the numbers in the above.
> 
> 1 A 0 G 19       =    1+0+19 = 20
> 
> 5 G 0 C 25 ^C 52  =   5+0+25+52 = 82
> 
> 0 G 2 T 3 T 91    =  0+2+3+91 =  96
> 44 ^C 70   =   44+70 =  114
> 
>  In first string 1A0G19  I am only adding 1, 0, and 19.    I am not
> splitting 19 to add 1+9 which will give totally wrong answer for me.
> 
> 
> Is there a way I can do this.
> 
> Thanks for your advise.
> 
> kumar
> 

There might be a better way, but you can use regular expressions.

>>> match = re.search( '(\d+)A(\d+)G(\d+)', '1A0G19' )
>>> map(int, match.groups() )
[1, 0, 19]
>>> sum( _ ) 
20


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list