What does {:<20} {:>4} mean in format_string?
Beginner
popularity = [["Language", 2017, 2012, 2007, 2002, 1997, 1992, 1987],
["Java", 1, 2, 1, 1, 15, 0, 0],
["C", 2, 1, 2, 2, 1, 1, 1],
["C++", 3, 3, 3, 3, 2, 2, 5],
["C#", 4, 4, 7, 13, 0, 0, 0],
["Python", 5, 7, 6, 11, 27, 0, 0],
["Visual Basic .NET", 6, 17, 0, 0, 0, 0, 0],
["PHP", 7, 6, 4, 5, 0, 0, 0],
["JavaScript", 8, 9, 8, 7, 23, 0, 0],
["Perl", 9, 8, 5, 4, 4, 10, 0]]
format_string = "{:<20} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4}"
Doc here:
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
'<': Forces the field to be left-aligned within the available space (this is the default for most objects).
'>': Forces the field to be right-aligned within the available space (this is the default for numbers).
So {:<20} means left-aligned with width 20. Similarly, {:>4} means right-aligned with width 4.
To see how it works:
for l in popularity: print(format_string.format(*l))
Output:
Language 2017 2012 2007 2002 1997 1992 1987
Java 1 2 1 1 15 0 0
C 2 1 2 2 1 1 1
C++ 3 3 3 3 2 2 5
C# 4 4 7 13 0 0 0
Python 5 7 6 11 27 0 0
Visual Basic .NET 6 17 0 0 0 0 0
PHP 7 6 4 5 0 0 0
JavaScript 8 9 8 7 23 0 0
Perl 9 8 5 4 4 10 0
By the way, Python ranked Top 1 in 2017, and stays on top in 2018.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With