4

I've seen a question on justifying a 'print' right, but could I have text left and right on the same line, for a --help? It'd look like this in the terminal:

|                                                     |
|Left                                            Right|
|                                                     |
tkbx
  • 14,366
  • 27
  • 82
  • 118

2 Answers2

4

I think you can use sys.stdout for this:

import sys

def stdout(message):
    sys.stdout.write(message)
    sys.stdout.write('\b' * len(message))   # \b: non-deleting backspace

def demo():
    stdout('Right'.rjust(50))
    stdout('Left')
    sys.stdout.flush()
    print()

demo()

You can replace 50 with the exact console width, which you can get from https://stackoverflow.com/a/943921/711085

Community
  • 1
  • 1
Blender
  • 275,078
  • 51
  • 420
  • 480
  • couldn't you use `print message,` (note trailing comma)? – andrew cooke Mar 09 '12 at 20:06
  • nifty. I've commented it, and edited it so it works in the interactive python prompt, and in both python2 and python3. Replace `50` with the value you'd get from http://stackoverflow.com/a/943921/711085 for exact accuracy. – ninjagecko Mar 09 '12 at 20:06
  • @andrewcooke: The `\b` "rewinds: the cursor to the beginning of the line, so I'm actually overwriting the line when I print out `Left`. You could use `print`, though. @FJ did. – Blender Mar 09 '12 at 20:21
  • 1
    right, but there's no need to mess around with sys.stdout, you can still use idiomatic python print (there's nothing special about \b that requires sys.stdout). – andrew cooke Mar 09 '12 at 20:29
3

Here is a pretty simple method:

>>> left, right = 'Left', 'Right'
>>> print '|{}{}{}|'.format(left, ' '*(50-len(left+right)), right)
|Left                                         Right|

As a function:

def lr_justify(left, right, width):
    return '{}{}{}'.format(left, ' '*(width-len(left+right)), right)

>>> lr_justify('Left', '', 50)
'Left                                              '
>>> lr_justify('', 'Right', 50)
'                                             Right'
>>> lr_justify('Left', 'Right', 50)
'Left                                         Right'
>>> lr_justify('', '', 50)
'                                                  '
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294