Specify it before the alignment character (> or <), without apostrophes.
contents = {"Introduction": 1, "Python Basics": 5, "Creating Your First Program": 12, "Operators and Variables": 29}
for chapt, page in contents.items():
print(f"{chapt:.<30}{page:.>5}")
Outputs:
Introduction......................1
Python Basics.....................5
Creating Your First Program......12
Operators and Variables..........29
From the documentation
Answer from pho on Stack OverflowIf a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (“
{” or “}”) as the fill character in a formatted string literal or when using thestr.format()method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect theformat()function
Specify it before the alignment character (> or <), without apostrophes.
contents = {"Introduction": 1, "Python Basics": 5, "Creating Your First Program": 12, "Operators and Variables": 29}
for chapt, page in contents.items():
print(f"{chapt:.<30}{page:.>5}")
Outputs:
Introduction......................1
Python Basics.....................5
Creating Your First Program......12
Operators and Variables..........29
From the documentation
If a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (“
{” or “}”) as the fill character in a formatted string literal or when using thestr.format()method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect theformat()function
According to the Format Specification Mini-Language you have to specify it before the "align":
contents = [('Introduction', 1), ('Python Basics', 5),
('Creating Your First Program', 12),
('Operators and Variables', 29)]
row_length = 35
for chapt, page in contents:
dots = str(row_length - len(str(page)))
print(f"{chapt:.<{dots}}{page}")
*This is now independent of the page number's length. A little bit more flexible.
f-string alignment
f-strings in Python 3.6 are awesome
I try to align multiple line of strings with print(f"{string:25}"), their lengths are the same, but they don't look aligned in Jupyter noteook, see screenshot: https://imgur.com/a/Oa1isra
Please kindly advise why this is the case.
In this statement print(f"|{students[i+j]:^{CELL_WIDTH}}", end='') the data type of variable CELL_WIDTH is float which is supposed to be int ..
Change the statement CELL_WIDTH = (LINE_WIDTH - STUDENTS_PER_ROW - 1) / STUDENTS_PER_ROW with CELL_WIDTH = (LINE_WIDTH - STUDENTS_PER_ROW - 1) // STUDENTS_PER_ROW which will make CELL_WIDTH datatype as int..
I think you'd need to add int() to your statement because CELL_WIDTH is a float value.
So:
CELL_WIDTH=int(LINE_WIDTH - STUDENTS_PER_ROW-1)/STUDENTS_PER_ROW
Hope that helps!