2

I need to write data to a textfile as a table. Sort of like a database. The header has Drivers, Cars, Teams, Grids, Fastest Lap, Race Time and Points. When I try to write the data that goes under it the don't line up. As some drivers names are longer than others.

It looks a bit like this:

|     Driver      |
|Sebastian William|
|Tom Hamilton  | 

Only 2 of the names actually align with the header. I am only trying to solve the issue with Drivers for now once I figure that out I should be able to gets all the other headers lined up.

Using a for loop through the array of dictionaries I set x to equal the len of the drivers name and 22 is the length of the longest name(18) plus a few spaces.

TextFile.write((items['Driver']+'\t|').expandtabs(22-x))

Any way of making them line up?

2 Answers 2

4

You could use format string syntax:

>>> "|{:22}|".format("Niki Lauda")
'|Niki Lauda            |'

You can also change the alignment:

>>> "|{:>22}|".format("Niki Lauda")
'|            Niki Lauda|'
>>> "|{:^22}|".format("Niki Lauda")
'|      Niki Lauda      |'

and if you want more flexibility with your column size, you can parametrize that as well:

>>> "|{:^{}}|".format("Niki Lauda", 24)
'|       Niki Lauda       |'
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know you could nest fields. It could get confusing with longer format strings. I think I would use field names in that case.
Field nesting is mentioned at the end of the Format String Syntax documentation and at the end of the examples.
2

On top of the answer provided by Tim, you could opt to use Tabulate which is very easy to use and customise.

table = [["spam",42],["eggs",451],["bacon",0]]
headers = ["item", "qty"]
print tabulate(table, headers, tablefmt="grid")

+--------+-------+
| item   |   qty |
+========+=======+
| spam   |    42 |
+--------+-------+
| eggs   |   451 |
+--------+-------+
| bacon  |     0 |
+--------+-------+

This provides support for multiple different database styles too. I prefer this to simply using format because it allows me to completely change the output style by configuring the tablefmt argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.