How do I set alignment and restrict character length in an f string?

467 Views Asked by At

I am trying to output from a CSV reader a table with three columns. Each column is formatted differently. The first column has a maximum and minimum of 44 characters.

This is the print statement:

print(f"{row[1] :<44s} | {row[2] :>5} | {row[0]} {i[0]}")

The spacing is correct but this statement allows more than 44 characters.

The output I get is this:

Wonders of the World                         |     G | 16:40 20:00
Journey to Space                             | PG-13 | 19:00
Buffalo Bill And The Indians or Sitting Bull's History Lesson |    PG | 15:00 19:30
Adventure of Lewis and Clark                 | PG-13 | 10:00 14:30

The output should look like this:

Wonders of the World                         |     G | 16:40 20:00
Journey to Space                             | PG-13 | 19:00
Buffalo Bill And The Indians or Sitting Bull |    PG | 15:00 19:30
Adventure of Lewis and Clark                 | PG-13 | 10:00 14:30
1

There are 1 best solutions below

0
Brandon Pardi On

You can easily limit char length with array slicing

strr = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'
print(f"{strr[:44]} | {strr :>5}")

Output you'll see the first column will limit the length compared to the second one

Lorem Ipsum is simply dummy text of the prin | Lorem Ipsum is simply dummy text of the printing and typesetting industry

Note it is a bit unclear when you say that the first column has a minimum and a maximum of 44 characters, so this answer applies to if you have a maximum of 44, however it can be easily adjusted .