Basic Python Alignment Trouble

Question:

I’m trying to align the a phrase and cannot get past syntax errors. This is my code:

print(f'{Rodneys Pricing Table:^10}')

Is there something I’m missing here? I want the phrase "Rodneys Pricing Table" to print center-aligned.

I’ve tried everything I’ve learned so far in my introductory programming class, I had alignment exercises I did and now I cannot get it to work here.

Asked By: squall1214

||

Answers:

f-strings are used to render expressions. Expression can have spaces, but then you wouldn’t need an f-string for that.

Instead, you could make a variable.

phrase = 'Rodneys Pricing Table'
print(f'{phrase:^10}')

However, "centering" text in the terminal is:

  1. Terminal dependent, not something print() knows about
    • The ^10 creates a string of at least ten "spaces", then puts your text within that, so…
  2. Not going to occur when ^10 is shorter than your string.

Refer Center-aligning text on console in Python

Answered By: OneCricketeer

The string needs to be quoted to work as a string constant, and the field width needs to be longer than 10 since the string itself is longer than that. Also make sure to use a different quote style than the f-string.

For example:

>>> print('1234567890'*4); print(f'{"Rodneys Pricing Table":^40}')
1234567890123456789012345678901234567890
         Rodneys Pricing Table
Answered By: Mark Tolonen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.