question about extracting value from a string

Discussion in 'Python' started by nephish, Dec 7, 2005.

  1. nephish

    nephish Guest

    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?

    nephish, Dec 7, 2005
    1. Advertisements

  2. 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 Martelli, Dec 7, 2005
    1. Advertisements

  3. nephish

    nephish Guest

    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.
    nephish, Dec 7, 2005
  4. 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 Martelli, Dec 7, 2005
  5. nephish

    nephish Guest

    I agree -- "to each day are sufficient the evils thereof". Many
    thats funny :)
    nephish, Dec 7, 2005
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.