how to improve this simple block of code

Discussion in 'Python' started by py, Jan 11, 2006.

  1. py

    py Guest

    Say I have...
    x = "132.00"

    but I'd like to display it to be "132" ...dropping the trailing
    zeros...I currently try this

    if x.endswith("0"):
    x = x[:len(x)-1]
    if x.endswith("0"):
    x = x[:len(x)-1]
    if x.endswith("."):
    x = x[:len(x)-1]

    I do it like this because if
    x = "132.15" ...i dont want to modify it. But if
    x = "132.60" ...I want it to become "132.6"

    is there a better way to do this? It seems a bit ugly to me.

    T.I.A
    (thanks in advance)
    py, Jan 11, 2006
    #1
    1. Advertising

  2. py

    Juho Schultz Guest

    py wrote:
    > Say I have...
    > x = "132.00"
    >
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...I currently try this
    >
    > if x.endswith("0"):
    > x = x[:len(x)-1]
    > if x.endswith("0"):
    > x = x[:len(x)-1]
    > if x.endswith("."):
    > x = x[:len(x)-1]
    >
    > I do it like this because if
    > x = "132.15" ...i dont want to modify it. But if
    > x = "132.60" ...I want it to become "132.6"
    >
    > is there a better way to do this? It seems a bit ugly to me.
    >
    > T.I.A
    > (thanks in advance)
    >


    x = x.rstrip('0') # removes trailing zeros
    x = x.rstrip('.') # removes trailing dot(s)
    Juho Schultz, Jan 11, 2006
    #2
    1. Advertising

  3. py

    hanz Guest

    Or combined:

    x = x.rstrip('0.') # removes trailing zeroes and dots
    hanz, Jan 11, 2006
    #3
  4. py

    py Guest

    hanz wrote:
    > x = x.rstrip('0.') # removes trailing zeroes and dots


    knew there had to be a way, thanks.
    py, Jan 11, 2006
    #4
  5. py

    Peter Otten Guest

    hanz wrote:

    > Or combined:
    >
    > x = x.rstrip('0.') # removes trailing zeroes and dots


    >>> "130.00".rstrip("0.")

    '13'

    Oops.

    Peter
    Peter Otten, Jan 11, 2006
    #5
  6. py

    Roy Smith Guest

    In article <>,
    "py" <> wrote:

    > Say I have...
    > x = "132.00"
    >
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...I currently try this



    This sounds to me like a job for regular expressions. Something like:

    re.sub (r'\.?0*$', '', x)

    will do what you want. Check out the re module in the docs for more
    details.
    Roy Smith, Jan 11, 2006
    #6
  7. py

    Matt Hammond Guest

    On Wed, 11 Jan 2006 13:58:05 -0000, py <> wrote:

    > Say I have...
    > x = "132.00"
    >
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...


    How about:

    if "." in x:
    x, frac = x.split(".")
    frac = frac.rstrip("0")
    if frac:
    x = x + "." + frac


    Copes if x = "132" too. If there'll always be a decimal point, then you
    can leave off the initial "if".



    Matt
    --

    | Matt Hammond
    | R&D Engineer, BBC Research & Development, Tadworth, Surrey, UK.
    | http://kamaelia.sf.net/
    | http://www.bbc.co.uk/rd/
    Matt Hammond, Jan 11, 2006
    #7
  8. py

    Mike Meyer Guest

    "py" <> writes:
    > Say I have...
    > x = "132.00"
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...I currently try this


    The two-strip solution is cleaner, but:

    > if x.endswith("0"):
    > x = x[:len(x)-1]

    x = x[:-1]
    or
    del x[-1]

    both improve that one statement.

    <mike
    --
    Mike Meyer <> http://www.mired.org/home/mwm/
    Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
    Mike Meyer, Jan 11, 2006
    #8
  9. py

    Peter Otten Guest

    Mike Meyer wrote:

    > "py" <> writes:
    >> Say I have...
    >> x = "132.00"
    >> but I'd like to display it to be "132" ...dropping the trailing
    >> zeros...I currently try this

    >
    > The two-strip solution is cleaner, but:
    >
    >> if x.endswith("0"):
    >> x = x[:len(x)-1]

    > x = x[:-1]
    > or
    > del x[-1]
    >
    > both improve that one statement.


    >>> del "it's tempting not to try"[-1]

    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: object doesn't support item deletion

    Just-pointing-out-what-does-not-work-ly yours

    Peter
    Peter Otten, Jan 11, 2006
    #9
  10. py

    Gary Duzan Guest

    py wrote:
    > x = "132.15" ...i dont want to modify it. But if
    > x = "132.60" ...I want it to become "132.6"
    >
    > is there a better way to do this? It seems a bit ugly to me.


    The following works as long as you don't mind losing leading zeros
    as well:

    x = x.strip('0')

    Gary Duzan
    Motorola CHS
    Gary Duzan, Jan 11, 2006
    #10
  11. py

    Matt Hammond Guest

    > How about:
    >
    > if "." in x:
    > x, frac = x.split(".")
    > frac = frac.rstrip("0")
    > if frac:
    > x = x + "." + frac


    Or simpler still:

    if "." in x:
    x = x.rstrip("0")
    x = x.rstrip(".")


    More concise, but slightly less readable IMO:

    if "." in x:
    x = x.rstrip("0").rstrip(".")

    --

    | Matt Hammond
    | R&D Engineer, BBC Research & Development, Tadworth, Surrey, UK.
    | http://kamaelia.sf.net/
    | http://www.bbc.co.uk/rd/
    Matt Hammond, Jan 11, 2006
    #11
  12. py

    Peter Hansen Guest

    py wrote:
    > hanz wrote:
    >>x = x.rstrip('0.') # removes trailing zeroes and dots

    >
    > knew there had to be a way, thanks.


    But that's not it. :)

    This is a wonderful opportunity for you to learn about unit testing, and
    begin the long process of developing good testing habits. Of all the
    ideas posted, I believe only Mark Hammond's would correctly pass the
    basic obvious test cases, and I don't think anyone (without actually
    having checked with tests) should be saying even his is clearly correct.

    import unittest
    from yourmodule import stripZeros # or whatever you have

    class Tests(unittest.TestCase):
    def test01(self):
    'check zero-stripper'
    for input, expected in [
    ('', ''),
    ('0', '0'),
    ('0.0', '0'),
    ('0.', '0'),
    ('000.', '000'),
    ('10', '10'),
    ('10.0', '10'),
    ('foo', 'foo'),
    ('foo.', 'foo'), # ??
    ('132.15', '132.15'),
    ('132.60', '132.6'),
    ('132.00', '132'),
    ('132.00000', '132'),
    ('132.000001', '132.000001'),
    # add others to taste
    ]:
    self.assertEquals(expected, stripZeros(input))

    unittest.main()


    Change the above test cases to match what you really want if they're not
    correct, then run the script and make sure everything passes.

    -Peter
    Peter Hansen, Jan 11, 2006
    #12
  13. py

    Peter Otten Guest

    Peter Hansen wrote:

    > Of all the ideas posted, I believe only Mark Hammond's would correctly
    > pass the basic obvious test cases


    Too bad he didn't post at all :)

    Peter
    Peter Otten, Jan 11, 2006
    #13
  14. py

    Peter Hansen Guest

    Peter Otten wrote:
    > Peter Hansen wrote:
    >>Of all the ideas posted, I believe only Mark Hammond's would correctly
    >>pass the basic obvious test cases

    >
    > Too bad he didn't post at all :)


    D'oh! There was a typo in my message above. Naturally, I meant to
    write "M. Hammond" instead of "Mark Hammond". ;-)

    Sorry Matt!

    -Peter
    Peter Hansen, Jan 11, 2006
    #14
  15. py

    Mel Wilson Guest

    py wrote:
    > Say I have...
    > x = "132.00"
    >
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...


    print '%g' % (float(x),)

    might work.

    Mel.
    Mel Wilson, Jan 11, 2006
    #15
  16. py

    Xavier Morel Guest

    Mel Wilson wrote:
    > py wrote:
    >> Say I have...
    >> x = "132.00"
    >>
    >> but I'd like to display it to be "132" ...dropping the trailing
    >> zeros...

    >
    > print '%g' % (float(x),)
    >
    > might work.
    >
    > Mel.
    >

    The input is a string, %g expects a float, TypeError exception.
    Xavier Morel, Jan 11, 2006
    #16
  17. py

    Xavier Morel Guest

    Forget about the previous mail, i just saw you were converting the
    string to float beforehand, in which case he would more than likely run
    into the good ol' float imprecision issue sooner than later.

    Not to mention that %g formats to scientific notation (e.g. exponential
    format with the exponent always being a multiple of 3), he'd probably
    use "%f".
    Xavier Morel, Jan 11, 2006
    #17
  18. On Wed, 11 Jan 2006 05:58:05 -0800, py wrote:

    > Say I have...
    > x = "132.00"
    >
    > but I'd like to display it to be "132" ...dropping the trailing
    > zeros...I currently try this


    Mucking about with the string is one solution. Here is another:

    print int(float(x))


    > I do it like this because if
    > x = "132.15" ...i dont want to modify it. But if
    > x = "132.60" ...I want it to become "132.6"


    Then you want:

    x = float("123.60") # full precision floating point value
    r = round(x, 1) # rounded to one decimal place



    --
    Steven.
    Steven D'Aprano, Jan 14, 2006
    #18
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gustavo Campanelli

    Newbie question: Any way to improve this code?

    Gustavo Campanelli, Dec 5, 2003, in forum: Python
    Replies:
    10
    Views:
    445
    Gustavo Campanelli
    Dec 7, 2003
  2. Jari Aalto
    Replies:
    4
    Views:
    475
    Robert Kern
    Oct 15, 2005
  3. Petr Jakes
    Replies:
    41
    Views:
    898
    Petr Jakes
    Jan 28, 2006
  4. morrell
    Replies:
    1
    Views:
    947
    roy axenov
    Oct 10, 2006
  5. Replies:
    14
    Views:
    522
Loading...

Share This Page