سؤال

I've a python script who display data in realtime(each second). I want to align these. I've try with pprint module but it doesnt works.

Example: My script displays this:

Server1 Sessions/s-----------------------Server2 Sessions/s

    64                                20
    0                                20
    64                                20
    64                                20
    64                                20
    0                                19
    128                                19
    0                                19
    256                                19
    192                                19

Is it possible to have this result?

Server1 Sessions/s----------------------Server2 Sessions/s

    64                               20
    0                                20
    64                               20
    64                               20
    64                               20
    0                                19
    128                              19
    0                                19
    256                              19
    192                              19

Each value are print every second. I haven't all of these in a list or a dictionary.

My code to display:

print("Server1 Sessions/s-----------------Server2 Sessions/s")
while i < self.timer:
    print("        " + str(self.serverrqs()*int(self.nbpro)) + "                                "+ str(self.servernbrqs()))
    i += 1
    sleep(1)

Thanks in advance

هل كانت مفيدة؟

المحلول

It should be the left alignment which specified by the '-' in the format string

print('        %-40s%s' % (self.serverrqs()*int(self.nbpro), self.servernbrqs()))

نصائح أخرى

You can just use string formatting:

>>> '%40s' % 'ab'
'                                      ab'

You could massage the following to fit:

from random import randint

for line in range(4):
    value1, value2 = randint(0, 16)*16, randint(19,20)
    print("    %-4i        %-4i" % (value1, value2))

The output of which looks like:

    144           20
    0             20
    96            20
    128           19

Google for: Python string interpolation, for more info.

With new-style (>=2.7) formatting

def format_row(leftval, rightval, width=30, fill=u' '):
    """"""
    row = u'        {0}{1:{fill}>{width}}'
    width = width - len(unicode(leftval))
    return row.format(leftval, rightval, fill=fill, width=width)

print format_row(1, 20)
print format_row(100, 20)
print format_row(100, 200)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top