Need help removing trailing zeros

Joshua Landau joshua.landau.ws at gmail.com
Wed Jun 26 19:05:39 EDT 2013


On 26 June 2013 23:21, PyNoob <bandcamp57 at gmail.com> wrote:
> Sorry about that... And thanks for your help, but I don't quite understand.
That's fine, but...

> Would that make it off your example print("{:g}".format(1.0))?
I don't understand this sentence.

But, hey, I forgot to check what level you were working at -- there's
little point running ahead of what you know.

Did you try:
    print("{:g}".format(1.0))
? It works for me. So, yes, that's what you want.

So instead of:
    print("The quotient of", A, "and", B, "is: ", Answer)

you want
    print("The quotient of", A, "and", B, "is: ", "{:g}".format(Answer))

See how I just used "{:g}".format as some kind of magic-fixing-power?

Well, why does it work?

[See http://docs.python.org/3/library/stdtypes.html#str.format and the
sub-links for a more full explanation]

Run each of these in an interpreter:

    "{} {} {} {} {}".format("This", "is", "a", "formatted", "string!")

    "It is really useful: I have {} cows and {}
sheep".format(number_of_cows, number_of_sheep)

    "It gives me back a formatted {}, which I can
print".format(type("".format()).__name__)

    "I can also give things indexes: {3} {2} {1} {0}".format("Print",
"in", "reverse", "order")

    "I can also give things names: {egg} {ham}
{flies}".format(egg="Are", ham="you", flies="there?")

    "It's not just {:!<10}".format("that")

    "It lets me choose how I want things to be printed: {0:@^6},
{0:~>10}, {0:£<8}".format("Hi")

    "And for numbers: {0:e}, {0:.10%}, {0:#.1f}".format(123.456)

So you just want the best formatter; see
[http://docs.python.org/3/library/string.html#format-specification-mini-language]

Your best choice is "{:g}" which just means "general format".

Note that you can also write your prints as so:

    print("The quotient of {} and {} is: {:g}".format(A, B, Answer))

Whether you prefer it is your choice.


------


In regards to .rstrip: It will only work on strings; so you need to
convert like so:
str(1.0).rstrip("0").rstrip(".")

And note that:
1) My .rstrip("0.") was wrong and foolish (try str(10).rstrip("0."))
2) This needs the string to be reliably formatted in this style:
"{:#f}" *and* requires it to be a float.

So really, you'd need:

"{:#f}".format(float(number)).rstrip("0").rstrip(".")

Which is ugly, but I guess it works.



More information about the Python-list mailing list