TIL 134 - = alignment in string formatting
Briefly

TIL 134 - = alignment in string formatting
"There are three main alignment options in Python's string formatting: However, numbers have a fourth option =. On the surface, it looks like it doesn't do anything: x = 73 print(f"@{x:10}@") # @ 73@ print(f"@{x:=10}@") # @ 73@ But that's because = influences the alignment of the sign. If I make x negative, we already see something: x = -73 print(f"@{x:10}@") # @ -73@ print(f"@{x:=10}@") # @- 73@ So, the equals sign = aligns a number to the right but aligns its sign to the left. That may look weird, but I guess that's useful if you want to pad a number with 0s: x = -73 print(f"@{x:010}@") # @-000000073@"
"In fact, there is a shortcut for this type of alignment, which is to just put a zero immediately to the left of the width when aligning a number: x = -73 print(f"@{x:010}@") # @-000000073@ In fact, there is a shortcut for this type of alignment, which is to just put a zero immediately to the left of the width when aligning a number: x = -73 print(f"@{x:010}@") # @-000000073@ The zero immediately to the left changes the default alignment of numbers to be = instead of >. Become a better Python 🐍 developer, drop by drop 💧 Get a daily drop of Python knowledge. A short, effective tip to start writing better Python code: more idiomatic, more effective, more efficient, with fewer bugs. Subscribe here."
Python's '=' alignment option separates sign placement from digit alignment for numeric formatting. The sign is placed left while the numeric digits are right-aligned inside the field. Negative numbers show the sign at the left edge of the field with padding or zeros between the sign and digits. A leading zero in the width specifier (for example :010) activates '=' alignment and fills the space between sign and digits with zeros. This produces consistent digit alignment and clear sign visibility for padded numeric output.
Read at Mathspp
Unable to calculate read time
[
|
]