Search code examples
pythontext-alignment

How can I format some numbers and have the space that is taken equally to each other?


My code looks something like this:

plants = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25"]
Grid_Of_Plants = """
|{}|{}|{}|{}|{}|
|{}|{}|{}|{}|{}|
|{}|{}|{}|{}|{}|
|{}|{}|{}|{}|{}|
|{}|{}|{}|{}|{}|
""".format(plants[0],plants[1],plants[2],plants[3],plants[4],plants[5],plants[6],plants[7],plants[8],plants[9],plants[10],plants[11],plants[12],plants[13],plants[14],plants[15],plants[16],plants[17],plants[18],plants[19],plants[20],plants[21],plants[22],plants[23],plants[24])
print(Grid_Of_Plants)

and if I run it, it turns into this:

|1|2|3|4|5|
|6|7|8|9|10|
|11|12|13|14|15|
|16|17|18|19|20|
|21|22|23|24|25|

As you can see, the space with the single-digit numbers isn't aligned properly. How can I fix it?


Solution

  • Right under the definition if the plants variable, add:

    plants = [i.rjust(2) for i in plants]
    

    Output:

    
    | 1| 2| 3| 4| 5|
    | 6| 7| 8| 9|10|
    |11|12|13|14|15|
    |16|17|18|19|20|
    |21|22|23|24|25|
    
    

    If there could be three-digit numbers, four-digit numbers, and so on, you can dynamically use that as the padding like so:

    pad = max(map(len, plants))
    plants = [i.rjust(pad) for i in plants]