Formatting Output

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • victor.herasme@gmail.com

    Formatting Output

    Hi,

    i am building a little script and i want to output a series of columns
    more or less like this:

    1 5 6
    2 2 8
    2 9 5

    The matter is that i don't know in advance how many columns there will
    be. By the way, each column will be actually FLOATs, not INTs. How can
    i do this ? Any help welcome. Regards,

    Victor
  • Marc 'BlackJack' Rintsch

    #2
    Re: Formatting Output

    On Mon, 02 Jun 2008 00:34:09 -0700, victor.herasme@ gmail.com wrote:
    i am building a little script and i want to output a series of columns
    more or less like this:
    >
    1 5 6
    2 2 8
    2 9 5
    >
    The matter is that i don't know in advance how many columns there will
    be. By the way, each column will be actually FLOATs, not INTs. How can
    i do this ? Any help welcome. Regards,
    Look at string methods, `join()` for example, and string formatting with
    the ``%`` operator.

    Ciao,
    Marc 'BlackJack' Rintsch

    Comment

    • Chris

      #3
      Re: Formatting Output

      On Jun 2, 9:34 am, "victor.hera... @gmail.com"
      <victor.hera... @gmail.comwrote :
      Hi,
      >
      i am building a little script and i want to output a series of columns
      more or less like this:
      >
      1  5  6
      2  2  8
      2  9  5
      >
      The matter is that i don't know in advance how many columns there will
      be. By the way, each column will be actually FLOATs, not INTs. How can
      i do this ? Any help welcome. Regards,
      >
      Victor
      import sys
      float_list = [1.0, 5.0, 6.0, 2.0, 2.0, 8.0, 2.0, 9.0, 5.0]
      num_columns = 3
      for i,item in enumerate(float _list):
      sys.stdout.writ e('%.4f\t' % item)
      if not (i+1) % num_columns:
      sys.stdout.writ e('\n')

      Problem with this approach is it doesn't cater for instances where you
      exceed the standard 80 characters for a terminal window.

      Comment

      • Mensanator

        #4
        Re: Formatting Output

        On Jun 2, 3:38 am, Chris <cwi...@gmail.c omwrote:
        On Jun 2, 9:34 am, "victor.hera... @gmail.com"
        >
        <victor.hera... @gmail.comwrote :
        Hi,
        >
        i am building a little script and i want to output a series of columns
        more or less like this:
        >
        1  5  6
        2  2  8
        2  9  5
        >
        The matter is that i don't know in advance how many columns there will
        be. By the way, each column will be actually FLOATs, not INTs. How can
        i do this ? Any help welcome. Regards,
        >
        Victor
        >
        import sys
        float_list = [1.0, 5.0, 6.0, 2.0, 2.0, 8.0, 2.0, 9.0, 5.0]
        num_columns = 3
        for i,item in enumerate(float _list):
            sys.stdout.writ e('%.4f\t' % item)
            if not (i+1) % num_columns:
                sys.stdout.writ e('\n')
        >
        Problem with this approach is it doesn't cater for instances where you
        exceed the standard 80 characters for a terminal window.
        That wouldn't be a problem if being re-directed to a file.

        A bigger problem would be if his list were actually

        [1.0,2.0,2.0,5.0 ,2.0,9.0,6.0,8. 0,5.0]

        but he still wanted it printed

        1 5 6
        2 2 8
        2 9 5

        as if he always wants 3 rows, but doesn't know how many columns
        it will take. In which case, he could do something like this:

        import sys
        float_list = [1.0,2.0,2.0,5.0 ,2.0,9.0,6.0,8. 0,5.0]
        num_rows = 3
        num_cols = divmod(len(floa t_list),num_row s)
        for r in xrange(num_rows ):
        for c in xrange(num_cols[0]):
        sys.stdout.writ e('%.4f\t' % float_list[c*num_rows + r])
        if num_cols[1]>0 and r<num_cols[1]:
        sys.stdout.writ e('%.4f\t' % float_list[(c+1)*num_rows + r])
        sys.stdout.writ e('\n')

        1.0000 5.0000 6.0000
        2.0000 2.0000 8.0000
        2.0000 9.0000 5.0000

        And then changing list size would merely add more columns, so

        [1.0,2.0,2.0,5.0 ,2.0,9.0,6.0,8. 0,5.0,6.6666]

        would print as

        1.0000 5.0000 6.0000 6.6666
        2.0000 2.0000 8.0000
        2.0000 9.0000 5.0000


        Comment

        • Doug Morse

          #5
          Re: Formatting Output

          On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator <mensanator@aol .comwrote:
          On Jun 2, 3:38 am, Chris <cwi...@gmail.c omwrote:
          On Jun 2, 9:34 am, "victor.hera... @gmail.com"

          <victor.hera... @gmail.comwrote :
          Hi,
          i am building a little script and i want to output a series of columns
          more or less like this:
          1  5  6
          2  2  8
          2  9  5
          ...
          I have a related question:

          Does Python have (or can emulate) the formatted output capability found in
          Perl?

          For example, all I have to do to get nicely formatted (i.e., aligned) output
          is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT,
          STDOUT_BOTTOM, etc.), exemplified by:


          format STDOUT_TOP =
          ------------------------------------------------------------------------------
          ~

          Comment

          • Chris

            #6
            Re: Formatting Output

            On Jun 2, 9:43 pm, Doug Morse <mo...@edoug.or gwrote:
            On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator <mensana...@aol .comwrote:
             On Jun 2, 3:38 am, Chris <cwi...@gmail.c omwrote:
            On Jun 2, 9:34 am, "victor.hera... @gmail.com"
            >
            <victor.hera... @gmail.comwrote :
            Hi,
            >
            i am building a little script and i want to output a series of columns
            more or less like this:
            >
            1  5  6
            2  2  8
            2  9  5
            ...
            >
            I have a related question:
            >
            Does Python have (or can emulate) the formatted output capability found in
            Perl?
            >
            For example, all I have to do to get nicely formatted (i.e., aligned) output
            is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT,
            STDOUT_BOTTOM, etc.), exemplified by:
            >
              format STDOUT_TOP =
              ------------------------------------------------------------------------------
              ~
              .
            >
              format STDOUT =
              @<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<
              $res->{'full_name' },  $res->{'phone_1'},         $res->{'phone_1_type '}
              @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
              $res->{'address_1a'} ,                $res->{'address_2a '}
              @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
              $res->{'address_1b'} ,                $res->{'address_2b '}
              @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
              $res->{'address_1c'} ,                $res->{'address_2c '}
              @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
              $city_1                              $city_2
              @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
              $res->{'email_1'},                   $res->{'email_2'}
              ------------------------------------------------------------------------------
              ~
              .
            >
            Then, all I have to do is populate my $res object/hash as desired -- in this
            example simple the results of a SQL query -- and lastly just call the "write"
            function:
            >
              write;
            >
            and Perl will produce very nicely formatted results.  This is useful notonly
            for producing human readable output, but also fixed-column-width data files,
            etc.  I'd love to learn the Pythonistic way of doing the same thing.
            >
            Thanks!
            Doug
            Can't seem to do this with dictionaries but...

            preformatted_st ring = """
            %s %20s %20s
            %s %30s
            %s %30s
            """

            print preformatted_st ring % ('first name'[:20], 'contact num 1'[:20],
            'contact num type'[:20], 'address line 1'[:30], 'address line
            2'[:30]
            'address line 3'[:30], 'address line 4'[:30])

            You could do something like that. the "[:20]" etc @ the end of the
            inputs is ofc to trim the strings to a max length. The string
            formatter supports "%<number of characters to move to the right>s" so
            you can use that for alignment. It's a bit late so maybe I buggered
            up when I tried to use dictionary assignment with it, but who knows :p

            Comment

            • Chris

              #7
              Re: Formatting Output

              On Jun 2, 11:34 pm, Chris <cwi...@gmail.c omwrote:
              On Jun 2, 9:43 pm, Doug Morse <mo...@edoug.or gwrote:
              >
              >
              >
              On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator <mensana...@aol .com>wrote:
               On Jun 2, 3:38 am, Chris <cwi...@gmail.c omwrote:
              On Jun 2, 9:34 am, "victor.hera... @gmail.com"
              >
              <victor.hera... @gmail.comwrote :
              Hi,
              >
              i am building a little script and i want to output a series of columns
              more or less like this:
              >
              1  5  6
              2  2  8
              2  9  5
              ...
              >
              I have a related question:
              >
              Does Python have (or can emulate) the formatted output capability found in
              Perl?
              >
              For example, all I have to do to get nicely formatted (i.e., aligned) output
              is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT,
              STDOUT_BOTTOM, etc.), exemplified by:
              >
                format STDOUT_TOP =
                ------------------------------------------------------------------------------
                ~
                .
              >
                format STDOUT =
                @<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<
                $res->{'full_name' },  $res->{'phone_1'},         $res->{'phone_1_type '}
                @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                $res->{'address_1a'} ,                $res->{'address_2a '}
                @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                $res->{'address_1b'} ,                $res->{'address_2b '}
                @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                $res->{'address_1c'} ,                $res->{'address_2c '}
                @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                $city_1                              $city_2
                @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                $res->{'email_1'},                   $res->{'email_2'}
                ------------------------------------------------------------------------------
                ~
                .
              >
              Then, all I have to do is populate my $res object/hash as desired -- in this
              example simple the results of a SQL query -- and lastly just call the "write"
              function:
              >
                write;
              >
              and Perl will produce very nicely formatted results.  This is useful not only
              for producing human readable output, but also fixed-column-width data files,
              etc.  I'd love to learn the Pythonistic way of doing the same thing.
              >
              Thanks!
              Doug
              >
              Can't seem to do this with dictionaries but...
              >
              preformatted_st ring = """
              %s %20s %20s
              %s %30s
              %s %30s
              """
              >
              print preformatted_st ring % ('first name'[:20], 'contact num 1'[:20],
                      'contact num type'[:20], 'address line 1'[:30], 'address line
              2'[:30]
                      'address line 3'[:30], 'address line 4'[:30])
              >
              You could do something like that.  the "[:20]" etc @ the end of the
              inputs is ofc to trim the strings to a max length.  The string
              formatter supports "%<number of characters to move to the right>s" so
              you can use that for alignment.  It's a bit late so maybe I buggered
              up when I tried to use dictionary assignment with it, but who knows :p
              Actually just realised I had the number on the wrong side... :D

              preformatted_st ring = """
              %(first_name)s %(contact_num)2 0s %(contact_type) 20s
              """
              print preformatted_st ring % {'first_name':' Chris',
              'contact_num':' 555-5555', 'contact_type': 'Home'}

              Comment

              • Mensanator

                #8
                Re: Formatting Output

                On Jun 2, 2:43 pm, Doug Morse <mo...@edoug.or gwrote:
                On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator <mensana...@aol .comwrote:
                 On Jun 2, 3:38 am, Chris <cwi...@gmail.c omwrote:
                On Jun 2, 9:34 am, "victor.hera... @gmail.com"
                >
                <victor.hera... @gmail.comwrote :
                Hi,
                >
                i am building a little script and i want to output a series of columns
                more or less like this:
                >
                1  5  6
                2  2  8
                2  9  5
                ...
                >
                I have a related question:
                >
                Does Python have (or can emulate) the formatted output capability found in
                Perl?
                >
                For example, all I have to do to get nicely formatted (i.e., aligned) output
                is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT,
                STDOUT_BOTTOM, etc.), exemplified by:
                >
                  format STDOUT_TOP =
                  ---------------------------------------------------------------------------­---
                  ~
                  .
                >
                  format STDOUT =
                  @<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<
                  $res->{'full_name' },  $res->{'phone_1'},         $res->{'phone_1_type '}
                  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                  $res->{'address_1a'} ,                $res->{'address_2a '}
                  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                  $res->{'address_1b'} ,                $res->{'address_2b '}
                  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                  $res->{'address_1c'} ,                $res->{'address_2c '}
                  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                  $city_1                              $city_2
                  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<<  @<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <<<<< ~
                  $res->{'email_1'},                   $res->{'email_2'}
                  ---------------------------------------------------------------------------­---
                  ~
                  .
                >
                Then, all I have to do is populate my $res object/hash as desired -- in this
                example simple the results of a SQL query -- and lastly just call the "write"
                function:
                >
                  write;
                >
                and Perl will produce very nicely formatted results.  This is useful notonly
                for producing human readable output, but also fixed-column-width data files,
                etc.  I'd love to learn the Pythonistic way of doing the same thing.
                >
                Thanks!
                Doug
                I didn't know you could do that in perl. Too bad I quit using it
                when I switched to Python.

                OTOH, I can do similar formatting directly in SQL.

                In Access, I create a query with this SQL:

                SELECT
                "------------------------------------------------------------" &
                Chr(10) &
                Format$(SampleE ventCode,"!@@@@ @@@@@@@@@@@@") &
                Format$
                (SampleEventDes cr,"@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@") &
                Chr(10) &
                Format$(EventSo rtOrder,"!@@@@@ @@@@@@@@@@@") &
                Format$("From: " & Format$(DateFro m,"YYYY/MM/
                DD"),"@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@") &
                Chr(10) &
                Format$(SampleE ventReportLabel ,"!@@@@@@@@@@@@ @@@@") &
                Format$("To: " & Format$(DateTo, "YYYY/MM/
                DD"),"@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@")
                AS Expr1
                FROM tblSampleEvent;

                Then I simply call it from Python. (I could call with the SQL code
                instead of invoking the Access query, but the OBDC interface can't
                process this particular SQL statement, tries to put brackets around
                the format templates, so best render unto Access the things that
                belong to Access.)

                # code
                import dbi
                import odbc
                con = odbc.odbc("BPWR ")
                cursor = con.cursor()
                cursor.execute( """
                SELECT * FROM SQLFormatTest;
                """)
                results = cursor.fetchall ()
                for i in results:
                for j in i:
                print j
                # /code

                which prints

                ------------------------------------------------------------
                2000Q1 First Quarter of 2000
                2000100 From: 2000/01/01
                1st-Qtr 2000 To: 2000/03/31
                ------------------------------------------------------------
                2000Q2 Second Quarter of 2000
                2000200 From: 2000/04/01
                2nd-Qtr 2000 To: 2000/06/30
                ------------------------------------------------------------
                2000Q3 Third Quarter of 2000
                2000300 From: 2000/07/01
                3rd-Qtr 2000 To: 2000/09/30
                ------------------------------------------------------------
                2000Q4 Fourth Quarter of 2000
                2000400 From: 2000/10/01
                4th-Qtr 2000 To: 2000/12/31
                ------------------------------------------------------------
                2000Q1LF Low Flow First Quarter of 2000
                2000105 From: 2000/01/01
                1st-Qtr 2000 To: 2000/03/31
                ------------------------------------------------------------
                2000Q2LOD LOD borings Second Quarter of 2000
                2000206 From: 2000/04/01
                2nd-Qtr 2000 To: 2000/06/30
                .
                .
                .

                Comment

                • TheSaint

                  #9
                  Re: Formatting Output

                  On 06:15, martedì 03 giugno 2008 Mensanator wrote:
                  In Access, I create a query with this SQL:
                  But this isn't python itself.
                  I'd like to see a small function to let 'locate' the cursor into a TTY
                  console. Surely it can't scroll.
                  If it is not possible, then ncurses is the way. I don't know if it works on
                  win32.

                  --
                  Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html

                  Comment

                  Working...