Skip to content

Instantly share code, notes, and snippets.

@newsch
Last active May 12, 2019 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newsch/06c167a6d9516dfc97474b484b74fd21 to your computer and use it in GitHub Desktop.
Save newsch/06c167a6d9516dfc97474b484b74fd21 to your computer and use it in GitHub Desktop.
Commandline script to center text
#!/usr/bin/env python3
"""Commandline script to center text horizontally."""
import argparse
def center(line: str, width: int, length: int = None):
"""Center a line within a width, optionally treating it as len length.
>>> center('foo', 6)
' foo'
>>> center('fo', 6)
' fo'
>>> center('foo', 3)
'foo'
>>> center('foo', 6, length=4)
' foo'
>>> center('foo', 9, length=5)
' foo'
"""
return ' '*((width - (len(line) if length is None else length)) // 2) + line
def fill(line: str, width: int):
"""Fill a line with trailing whitespace to width.
>>> fill('foo', 6)
'foo '
>>> fill('foo', 3)
'foo'
>>> fill('foo', 2)
'foo'
"""
return line + ' '*(width-len(line))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Center text horizontally e.g. "foo" -> " foo "')
parser.add_argument('infile', type=argparse.FileType('r'),
help='Input file (use `-` for stdin).')
parser.add_argument('-w', '--width', type=int, default=80,
help='Width to center within (default: 80).')
parser.add_argument('-v', '--vertical', type=int, help='Center vertically for the given height in lines.')
parser.add_argument('-f', '--fill', action='store_true', help='Add trailing lines and spaces.')
parser.add_argument('--line', action='store_true', help='Center on a line-by-line basis, instead of the longest line in the file.')
args = parser.parse_args()
lines = [line.strip('\n') for line in args.infile.readlines()]
lens = [len(line) for line in lines]
max_len = max(lens)
lines = list(map(lambda l: center(l, width=args.width, length=(None if args.line else max_len)), lines))
if args.vertical is not None:
lines = (['']*((args.vertical - len(lines)) // 2)) + lines
if args.fill:
if args.vertical is not None:
lines.extend(['']*(args.vertical - len(lines)))
lines = list(map(lambda l: fill(l, width=args.width), lines))
[print(line) for line in lines] # spit back out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment