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.
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:
- Terminal dependent, not something
print()
knows about
- The
^10
creates a string of at least ten "spaces", then puts your text within that, so…
- Not going to occur when
^10
is shorter than your string.
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
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.
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:
- Terminal dependent, not something
print()
knows about- The
^10
creates a string of at least ten "spaces", then puts your text within that, so…
- The
- Not going to occur when
^10
is shorter than your string.
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