question about extracting value from a string

N

nephish

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?

thanks
 
A

Alex Martelli

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
 
N

nephish

the second line was not a typo , and thanks for that.
these values may vary somewhat over time. So i may have to rewrite this
part of the script.

a string is fine for right now, because it is just going to be pumped
into a database. i can change it later if necessary.

thanks for the help gents, i am going to just go with string functions,
seems like it will be easier both to code now. and later if and when
the format of this stuff may change.
 
A

Alex Martelli

thanks for the help gents, i am going to just go with string functions,
seems like it will be easier both to code now. and later if and when
the format of this stuff may change.

I agree -- "to each day are sufficient the evils thereof". Many
programmers fall into the temptation to overgeneralize and fail to
follow the AGNI principle ("Ain't Gonna Need It"...;-).


Alex
 
N

nephish

I agree -- "to each day are sufficient the evils thereof". Many
programmers fall into the temptation to overgeneralize and fail to
follow the AGNI principle ("Ain't Gonna Need It"...;-).

thats funny :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top