Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting list in python

I have a list containing the numbers 25-1. I'm trying to print it out like a gameboard, where all the numbers match up:

enter image description here

I found out how to add the lines to the list by doing this:

_b = map(str, board)
_board = ' | '.join(_b)

and I know how to print 5 numbers on each line.. but I'm having trouble getting all the numbers to line up. Is there a way to do this?

like image 560
mdegges Avatar asked Dec 07 '25 10:12

mdegges


1 Answers

If you know how long the longest number is going to be, you can use any of these methods:

With the string "5" and a desired width of 3 characters:

  • str.rjust(3) will give the string ' 5'
  • str.ljust(3) will give the string '5 '
  • str.center(3) will give the string ' 5 '.

I tend to like rjust for numbers, as it lines up the places like you learn how to do long addition in elementary school, and that makes me happy ;)

That leaves you with something like:

_b = map(lambda x: str(x).rjust(3), board)
_board = ' | '.join(_b)

or alternately, with generator expressions:

_board = ' | '.join(str(x).rjust(3) for x in board)
like image 128
Crast Avatar answered Dec 10 '25 00:12

Crast