question about extracting value from a string

Alex Martelli aleax at mail.comcast.net
Wed Dec 7 10:41:39 EST 2005


<nephish at xit.net> wrote:

> hey there,
> 
> i have looked at the string module and re.
> i was looking for advice on what would be the best way to pull a value
> out of a small string.
> 
> for example, i have a string
> $.+.09 JAR
>    and all i want out of it is the +.09
> 
> likewise, i have
> $-.04 TIN kt
>   and all i want is the -.04
> 
> what would be my best bet here ?
> do i need a full blown re comparison? 

You can do it by pure string operations, if you wish -- e.g., if your
examples exhaust the possible issues, astring[1:5] will work for both.
It's hard to say whether it's best to use REs instead without having any
idea of the variety of formats your "value" can take and how differently
it might be placed inside the string, of course.

Once you do get the value, either by string slicing or REs, you'll have
a string -- if what you want is a float, call e.g. float(astring[1:5]);
or for a decimal number, decimal.Decimal(astring[1:5]) (after importing
module decimal from Python's standard library); and so on.


Alex



More information about the Python-list mailing list