[Tutor] Question About the .format Method.
Peter Otten
__peter__ at web.de
Thu Nov 10 04:08:54 EST 2016
Bryon Adams wrote:
> Hello,
> Working on a simple function to get an IP address and make it look
> pretty for the PyNet course. I'm wondering if there's way to evenly
> space text with the string.format() method similar to how I'm doing it
> with the % operator. The last two prints keep everything left aligned
> and 20 spaces wide. Is there a way to accomplish this with the .format()
> method that I use in the first print function?
You can left-align, center or right-align with format():
>>> print("| {:<12} | {:^12} | {:>12} |".format("left", "center", "right"))
| left | center | right |
The default is right-align for numbers and left-align for strings:
>>> "{:12}".format(42)
' 42'
>>> "{:12}".format("42")
'42 '
You can find the details here:
<https://docs.python.org/3.5/library/string.html#formatspec>
More information about the Tutor
mailing list