left padding zeroes on a string...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cjl

    #1

    left padding zeroes on a string...

    Hey all:

    I want to convert strings (ex. '3', '32') to strings with left padded
    zeroes (ex. '003', '032'), so I tried this:

    string1 = '32'
    string2 = "%03s" % (string1)
    print string2
    [color=blue]
    >32[/color]

    This doesn't work. If I cast string1 as an int it works:

    string1 = '32'
    int2 = "%03d" % (int(string1))
    print int2
    [color=blue]
    >032[/color]

    Of course, I need to cast the result back to a string to use it. Why
    doesn't the first example work?

    -cjl

  • Peter Hansen

    #2
    Re: left padding zeroes on a string...

    cjl wrote:[color=blue]
    > Hey all:
    >
    > I want to convert strings (ex. '3', '32') to strings with left padded
    > zeroes (ex. '003', '032'), so I tried this:
    >
    > string1 = '32'
    > string2 = "%03s" % (string1)[/color]

    string1.zfill(3 )

    -Peter

    Comment

    • George Sakkis

      #3
      Re: left padding zeroes on a string...

      "cjl" <cjlesh@gmail.c om> wrote:
      [color=blue]
      > Hey all:
      >
      > I want to convert strings (ex. '3', '32') to strings with left padded
      > zeroes (ex. '003', '032'), so I tried this:
      >
      > string1 = '32'
      > string2 = "%03s" % (string1)
      > print string2
      >[color=green]
      > >32[/color]
      >
      > This doesn't work.[/color]

      Actually in this case string2 is padded with spaces, instead of zeros.
      [color=blue]
      >If I cast string1 as an int it works:
      >
      > string1 = '32'
      > int2 = "%03d" % (int(string1))
      > print int2
      >[color=green]
      > >032[/color]
      >
      > Of course, I need to cast the result back to a string to use it. Why
      > doesn't the first example work?[/color]

      That's not correct; int2 is a string so you can use it directly (and probably rename it to something
      more appropriate).
      [color=blue]
      > -cjl[/color]

      Regards,
      George


      ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~
      "To see victory only when it is within the ken of the common herd is not
      the acme of excellence."

      Sun Tzu, 'The Art of War'
      ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~


      Comment

      • M.E.Farmer

        #4
        Re: left padding zeroes on a string...

        Your first conversion works fine.
        string1 = '32'
        string2 = "%04s" % (string1)
        print string2
        ' 32'
        Notice that it returns a string with spaces padding the left side.
        If you want to pad a number with 0's on the left you need to use
        zfill()
        '32'.zfill(4)
        '0032'
        Be sure to study up on string methods, it will save you time and
        sanity.
        Py> dir('')
        ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
        '__eq__', '__ge__', '__getattribute __', '__getitem__', '__getslice__',
        '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
        '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
        '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
        'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
        'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
        'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
        'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
        'swapcase', 'title', 'translate', 'upper', 'zfill']
        Py> help(''.zfill)
        Help on built-in function zfill:

        zfill(...)
        S.zfill(width) -> string

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        Hth,
        M.E.Farmer

        Comment

        • John Machin

          #5
          Re: left padding zeroes on a string...


          cjl wrote:[color=blue]
          > I want to convert strings (ex. '3', '32') to strings with left padded
          > zeroes (ex. '003', '032'), so I tried this:
          >
          > string1 = '32'
          > string2 = "%03s" % (string1)
          > print string2
          >[color=green]
          > >32[/color]
          >
          > This doesn't work.[/color]

          Documentation == """
          Flag Meaning
          0 The conversion will be zero padded for numeric values.
          """

          "Numeric values" means when converting from a numeric value as in
          "%03d", but not "%03s". If you think "numeric values" is vague or
          misleading -- K&R (v2 p243) has "numeric conversions" -- then submit a
          documentation patch.
          [color=blue]
          > If I cast string1 as an int it works:[/color]

          Python doesn't have casts. You mean "convert".

          You may like to consider the zfill method of string objects:
          [color=blue][color=green][color=darkred]
          >>> "3".zfill(5 )[/color][/color][/color]
          '00003'

          or the even more versatile rjust method:
          [color=blue][color=green][color=darkred]
          >>> "3".rjust(5 , '0')[/color][/color][/color]
          '00003'[color=blue][color=green][color=darkred]
          >>> "3".rjust(5 , '*')[/color][/color][/color]
          '****3'[color=blue][color=green][color=darkred]
          >>>[/color][/color][/color]

          HTH,
          John

          Comment

          • Kent Johnson

            #6
            Re: left padding zeroes on a string...

            cjl wrote:[color=blue]
            > Hey all:
            >
            > I want to convert strings (ex. '3', '32') to strings with left padded
            > zeroes (ex. '003', '032')[/color]

            In Python 2.4 you can use rjust with the optional fill argument:[color=blue][color=green][color=darkred]
            >>> '3'.rjust(3, '0')[/color][/color][/color]
            '003'

            In earlier versions you can define your own:[color=blue][color=green][color=darkred]
            >>> def rjust(s, l, c):[/color][/color][/color]
            ... return ( c*l + s )[-l:]
            ...[color=blue][color=green][color=darkred]
            >>> rjust('3', 3, '0')[/color][/color][/color]
            '003'[color=blue][color=green][color=darkred]
            >>> rjust('32', 3, '0')[/color][/color][/color]
            '032'

            Kent

            Comment

            • George Sakkis

              #7
              str vs dict API size (was 'Re: left padding zeroes on a string...')

              "M.E.Farmer " <mefjr75@hotmai l.com> wrote:[color=blue]
              >
              > [snipped]
              >
              > Be sure to study up on string methods, it will save you time and
              > sanity.
              > Py> dir('')
              > ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
              > '__eq__', '__ge__', '__getattribute __', '__getitem__', '__getslice__',
              > '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
              > '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
              > '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
              > 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
              > 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
              > 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
              > 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
              > 'swapcase', 'title', 'translate', 'upper', 'zfill'][/color]

              I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
              of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
              for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
              insight ?

              George


              ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~
              "Oh divine art of subtlety and secrecy! Through you we learn to be
              invisible, through you inaudible and hence we can hold the enemy's fate
              in our hands."

              Sun Tzu, 'The Art of War'
              ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~


              Comment

              • Larry Bates

                #8
                Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

                Once it is in everyone is hesitant to take it out for fear of
                breaking someone's code that uses it (no matter how obscure).
                Putting in new methods should be difficult and require lots
                of review for that reason and so we don't have language bloat.

                Larry Bates


                George Sakkis wrote:[color=blue]
                > "M.E.Farmer " <mefjr75@hotmai l.com> wrote:
                >[color=green]
                >>[snipped]
                >>
                >>Be sure to study up on string methods, it will save you time and
                >>sanity.
                >>Py> dir('')
                >>['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
                >>'__eq__', '__ge__', '__getattribute __', '__getitem__', '__getslice__',
                >>'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
                >>'__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
                >>'__setattr__' , '__str__', 'capitalize', 'center', 'count', 'decode',
                >>'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
                >>'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
                >>'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
                >>'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
                >>'swapcase', 'title', 'translate', 'upper', 'zfill'][/color]
                >
                >
                > I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
                > of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
                > for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
                > insight ?
                >
                > George
                >
                >
                > ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~
                > "Oh divine art of subtlety and secrecy! Through you we learn to be
                > invisible, through you inaudible and hence we can hold the enemy's fate
                > in our hands."
                >
                > Sun Tzu, 'The Art of War'
                > ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~
                >
                >[/color]

                Comment

                • George Sakkis

                  #9
                  Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

                  "Larry Bates" <lbates@syscono nline.com> wrote in message news:YOKdnQbt1q RGAdnfRVn-tg@comcast.com. ..[color=blue]
                  > Once it is in everyone is hesitant to take it out for fear of
                  > breaking someone's code that uses it (no matter how obscure).
                  > Putting in new methods should be difficult and require lots
                  > of review for that reason and so we don't have language bloat.
                  >
                  > Larry Bates[/color]

                  Language bloat is subjective of course, but I fail to see why putting in dict.reset and dict.add
                  should be harder than, say, str.swapcase or str.capitalize.

                  George




                  Comment

                  • Robert Kern

                    #10
                    Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

                    George Sakkis wrote:[color=blue]
                    > "Larry Bates" <lbates@syscono nline.com> wrote in message news:YOKdnQbt1q RGAdnfRVn-tg@comcast.com. ..
                    >[color=green]
                    >>Once it is in everyone is hesitant to take it out for fear of
                    >>breaking someone's code that uses it (no matter how obscure).
                    >>Putting in new methods should be difficult and require lots
                    >>of review for that reason and so we don't have language bloat.
                    >>
                    >>Larry Bates[/color]
                    >
                    >
                    > Language bloat is subjective of course, but I fail to see why putting in dict.reset and dict.add
                    > should be harder than, say, str.swapcase or str.capitalize.[/color]

                    Those were functions in the string module for, well much longer than I
                    can remember. When string methods were innovated, they became methods
                    along with the rest of the string module functions.

                    Adding functions was easier back then; the standard library was rather
                    smaller. There is no reason that the criteria for inclusion now must be
                    the same as then and plenty of good reasons for them to be more
                    restrictive now.

                    --
                    Robert Kern
                    rkern@ucsd.edu

                    "In the fields of hell where the grass grows high
                    Are the graves of dreams allowed to die."
                    -- Richard Harter

                    Comment

                    • Ron_Adam

                      #11
                      Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

                      On Fri, 25 Mar 2005 18:06:11 -0500, "George Sakkis"
                      <gsakkis@rutger s.edu> wrote:
                      [color=blue]
                      >
                      >I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
                      >of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
                      >for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
                      >insight ?
                      >
                      >George
                      >[/color]

                      I did a quick check.
                      [color=blue][color=green][color=darkred]
                      >>> len(dir(str))[/color][/color][/color]
                      63[color=blue][color=green][color=darkred]
                      >>> len(dir(int))[/color][/color][/color]
                      53[color=blue][color=green][color=darkred]
                      >>> len(dir(float))[/color][/color][/color]
                      45[color=blue][color=green][color=darkred]
                      >>> len(dir(dict))[/color][/color][/color]
                      40[color=blue][color=green][color=darkred]
                      >>> len(dir(list))[/color][/color][/color]
                      42[color=blue][color=green][color=darkred]
                      >>> len(dir(tuple))[/color][/color][/color]
                      27

                      We need more tuple methods! jk ;)

                      Looks like the data types, strings, int an float; have more methods
                      than dict, list, and tuple. I would expect that because there is more
                      ways to manipulate data than is needed to manage containers.

                      Ron


                      Comment

                      • Bengt Richter

                        #12
                        Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

                        On Sat, 26 Mar 2005 04:10:21 GMT, Ron_Adam <radam2@tampaba y.rr.com> wrote:
                        [color=blue]
                        >On Fri, 25 Mar 2005 18:06:11 -0500, "George Sakkis"
                        ><gsakkis@rutge rs.edu> wrote:
                        >[color=green]
                        >>
                        >>I'm getting off-topic here, but it strikes me that strings have so many methods (some of which are
                        >>of arguable utility, e.g. swapcase), while proposing two useful methods (http://tinyurl.com/5nv66)
                        >>for dicts -- a builtin with a considerably smaller API than str -- meets so much resistance. Any
                        >>insight ?
                        >>
                        >>George
                        >>[/color]
                        >
                        >I did a quick check.
                        >[color=green][color=darkred]
                        >>>> len(dir(str))[/color][/color]
                        >63[color=green][color=darkred]
                        >>>> len(dir(int))[/color][/color]
                        >53[color=green][color=darkred]
                        >>>> len(dir(float))[/color][/color]
                        >45[color=green][color=darkred]
                        >>>> len(dir(dict))[/color][/color]
                        >40[color=green][color=darkred]
                        >>>> len(dir(list))[/color][/color]
                        >42[color=green][color=darkred]
                        >>>> len(dir(tuple))[/color][/color]
                        >27
                        >
                        >We need more tuple methods! jk ;)
                        >
                        >Looks like the data types, strings, int an float; have more methods
                        >than dict, list, and tuple. I would expect that because there is more
                        >ways to manipulate data than is needed to manage containers.
                        >[/color]
                        More data:
                        [color=blue][color=green][color=darkred]
                        >>> for n,k in sorted((len(dir (v)),k) for k,v in ((k,v) for k,v in vars(__builtins __).items()[/color][/color][/color]
                        ... if isinstance(v, type))): print '%4s: %s' %(n,k)
                        ...
                        12: basestring
                        12: object
                        13: classmethod
                        13: staticmethod
                        14: enumerate
                        15: reversed
                        16: super
                        16: xrange
                        17: slice
                        18: property
                        23: buffer
                        27: tuple
                        27: type
                        34: file
                        34: open
                        37: frozenset
                        40: dict
                        42: list
                        45: float
                        48: complex
                        50: set
                        53: bool
                        53: int
                        53: long
                        60: unicode
                        63: str

                        Hm, I guess that includes inheritance, and they should be callable, so maybe (not researched)
                        [color=blue][color=green][color=darkred]
                        >>> for n,k in sorted((sum(cal lable(m) for k,m in vars(v).items() ),k)[/color][/color][/color]
                        ... for k,v in ((k,v) for k,v in vars(__builtins __).items()
                        ... if isinstance(v, type))): print '%4s: %s' %(n,k)
                        ...
                        1: basestring
                        4: classmethod
                        4: enumerate
                        4: staticmethod
                        5: reversed
                        5: super
                        6: property
                        6: slice
                        7: xrange
                        9: bool
                        10: object
                        10: type
                        16: buffer
                        19: tuple
                        22: file
                        22: open
                        30: frozenset
                        33: dict
                        35: list
                        38: float
                        39: complex
                        44: set
                        46: int
                        46: long
                        53: unicode
                        56: str

                        Regards,
                        Bengt Richter

                        Comment

                        Working...