Simple string formatting question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Steven D'Aprano

    #1

    Simple string formatting question

    I have a sinking feeling I'm missing something really,
    really simple.

    I'm looking for a format string similar to '%.3f'
    except that trailing zeroes are not included.

    To give some examples:

    Float String
    1.0 1
    1.1 1.1
    12.1234 12.123
    12.0001 12

    and similar.

    Here is a (quick and dirty) reference implementation:

    def format(f, width=3):
    fs = '%%.%df' % width
    s = fs % f
    return s.rstrip('0').r strip('.')


    Is there a way of getting the same result with just a
    single string format expression?



    --
    Steven

  • Ben Finney

    #2
    Re: Simple string formatting question

    "Steven D'Aprano" <steve@REMOVEME cyber.com.au> writes:
    [color=blue]
    > I have a sinking feeling I'm missing something really, really
    > simple.[/color]

    "Oh no, everyone in the galaxy gets that, that's perfectly natural
    paranoia."
    [color=blue]
    > I'm looking for a format string similar to '%.3f' except that
    > trailing zeroes are not included.[/color]

    Can;t be done, to my knowledge. You specify a particular precision,
    and the number will be formatted at that precision. This matches the
    'printf' behaviour that inspired string formatting operations.

    If your brute-force approach works, stick to that until you have a
    reason to look for something better.

    --
    \ "I have an answering machine in my car. It says, 'I'm home now. |
    `\ But leave a message and I'll call when I'm out.'" -- Steven |
    _o__) Wright |
    Ben Finney

    Comment

    • Fredrik Lundh

      #3
      Re: Simple string formatting question

      Steven D'Aprano wrote:
      [color=blue]
      > Here is a (quick and dirty) reference implementation:
      >
      > def format(f, width=3):
      > fs = '%%.%df' % width
      > s = fs % f
      > return s.rstrip('0').r strip('.')
      >
      > Is there a way of getting the same result with just a
      > single string format expression?[/color]

      not with % itself, but you can do it all in one line:

      def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

      </F>



      Comment

      • Paul McGuire

        #4
        Re: Simple string formatting question

        "Fredrik Lundh" <fredrik@python ware.com> wrote in message
        news:mailman.41 81.1144326919.2 7775.python-list@python.org ...[color=blue]
        > Steven D'Aprano wrote:
        >[color=green]
        > > Here is a (quick and dirty) reference implementation:
        > >
        > > def format(f, width=3):
        > > fs = '%%.%df' % width
        > > s = fs % f
        > > return s.rstrip('0').r strip('.')
        > >
        > > Is there a way of getting the same result with just a
        > > single string format expression?[/color]
        >
        > not with % itself, but you can do it all in one line:
        >
        > def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )
        >
        > </F>
        >
        >
        >[/color]
        Ooops, don't combine the two calls to rstrip().

        def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

        print format(3.140)
        print format(3.000)
        print format(3.000000 1)
        print format(30.0000)
        print format(300000.0 00)

        Gives:
        3.14
        3
        3
        3
        3

        But this works fine:
        def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0") .rstrip(".")


        -- Paul




        Comment

        • Steven D'Aprano

          #5
          Re: Simple string formatting question

          On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:
          [color=blue]
          > "Steven D'Aprano" <steve@REMOVEME cyber.com.au> writes:[/color]
          [color=blue][color=green]
          >> I'm looking for a format string similar to '%.3f' except that
          >> trailing zeroes are not included.[/color]
          >
          > Can;t be done, to my knowledge. You specify a particular precision,
          > and the number will be formatted at that precision. This matches the
          > 'printf' behaviour that inspired string formatting operations.
          >
          > If your brute-force approach works, stick to that until you have a
          > reason to look for something better.[/color]

          Thanks to everybody who replied, I'm glad to see I didn't miss anything.

          I do actually have a reason for wanting a single format pattern, but I can
          probably work with what I have, it will just be less convenient.

          I hesitate to suggest this, what with the whole PEP procedure and all
          being so intimidating to those who aren't familiar with it (e.g. me), but
          would there be any interest in extending the formatting operations to
          include such a feature? It would (presumably) break compatibility with
          printf, but does that matter?



          --
          Steven.

          Comment

          • Ben Finney

            #6
            Re: Simple string formatting question

            "Steven D'Aprano" <steve@REMOVETH IScyber.com.au> writes:
            [color=blue]
            > On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:[color=green]
            > > "Steven D'Aprano" <steve@REMOVEME cyber.com.au> writes:[/color][/color]
            1> >> I'm looking for a format string similar to '%.3f' except that[color=blue][color=green][color=darkred]
            > >> trailing zeroes are not included.[/color]
            > >
            > > Can;t be done, to my knowledge. You specify a particular
            > > precision, and the number will be formatted at that
            > > precision. This matches the 'printf' behaviour that inspired
            > > string formatting operations.[/color]
            >
            > [...] would there be any interest in extending the formatting
            > operations to include such a feature? It would (presumably) break
            > compatibility with printf, but does that matter?[/color]

            -1 from me. The concept of "precision" is fairly well defined; you're
            talking about combining that with something more special-case. In
            general, "special cases aren't special enough to break the rules", and
            the programemr should be forced to spell out what he's doing so that
            it's obvious.

            In the specific cases of the string formatting codes, they're a
            special case that is a marginal win because of the large body of
            existing experience with the standard C printf codes. That's weighed
            against their considerable lack of readability; expand them to be
            special for Python, and that "marginal win" is gone.

            --
            \ "My girlfriend has a queen sized bed; I have a court jester |
            `\ sized bed. It's red and green and has bells on it, and the ends |
            _o__) curl up." -- Steven Wright |
            Ben Finney

            Comment

            • Fredrik Lundh

              #7
              Re: Simple string formatting question

              Paul McGuire wrote:
              [color=blue]
              > Ooops, don't combine the two calls to rstrip().
              >
              > def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )
              >
              > print format(3.140)
              > print format(3.000)
              > print format(3.000000 1)
              > print format(30.0000)
              > print format(300000.0 00)[/color]

              hey, I'm doing test-driven development. being able to handle 30 and
              300000 wasn't part of the original spec ;-)
              [color=blue]
              > But this works fine:
              > def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0") .rstrip(".")[/color]

              indeed.

              </F>



              Comment

              • Peter Otten

                #8
                Re: Simple string formatting question

                Steven D'Aprano wrote:
                [color=blue]
                > I have a sinking feeling I'm missing something really,
                > really simple.
                >
                > I'm looking for a format string similar to '%.3f'
                > except that trailing zeroes are not included.
                >
                > To give some examples:
                >
                > Float String
                > 1.0 1
                > 1.1 1.1
                > 12.1234 12.123
                > 12.0001 12
                >
                > and similar.
                >
                > Here is a (quick and dirty) reference implementation:
                >
                > def format(f, width=3):
                > fs = '%%.%df' % width
                > s = fs % f
                > return s.rstrip('0').r strip('.')
                >
                >
                > Is there a way of getting the same result with just a
                > single string format expression?[/color]

                Does it have to be a string or can you cheat? If so:
                [color=blue][color=green][color=darkred]
                >>> class Format(str):[/color][/color][/color]
                .... def __new__(cls, width):
                .... return str.__new__(cls , "%%.%df" % width)
                .... def __mod__(self, other):
                .... return str.__mod__(sel f, other).rstrip(" 0").rstrip(" .")
                ....[color=blue][color=green][color=darkred]
                >>> format = Format(3)
                >>> for f in [1.0, 1.1, 12.1234, 12.0001]:[/color][/color][/color]
                .... print f, "-->", format % f
                ....
                1.0 --> 1
                1.1 --> 1.1
                12.1234 --> 12.123
                12.0001 --> 12

                For passing around in your app that should be as convenient as a string --
                of course it will break if you store the "format" in a file, say.

                Peter

                Comment

                Working...