-1

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.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
squall1214
  • 11
  • 3

2 Answers2

3

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thank you, I didn't understand that the number being specified is the amount of space I'm giving the string. – squall1214 Mar 30 '23 at 22:05
0

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 2
    f-strings are used to render ̶v̶a̶r̶i̶a̶b̶l̶e̶s̶ expressions (ie. `print(f'{"Rodneys Pricing Table":^10}')` would work if the available space was more than 10) – SuperStormer Mar 30 '23 at 21:50
  • 3
    You can put any expression inside `{}`. So you can put a quoted string literal. – Barmar Mar 30 '23 at 21:51
  • 2
    It would be more accurate to say that `^10` creates a string *at least* 10 characters wide, which will be padded on the left and right as needed if `phrase` is not itself at least 10 characters. – chepner Mar 30 '23 at 21:59