String Formatting

In [1]:
change = 1.5
In [2]:
print(change)
1.5
In [5]:
print("The total value of your change is ${0:0.2f}.".format(change))
The total value of your change is $1.50.
In [6]:
change_str = "The total value of your change is ${0:0.2f}."
print(change_str.format(change))
The total value of your change is $1.50.
In [9]:
# Don't do this, always number your slots
print("The total value of your change is ${:0.2f}.".format(change))
The total value of your change is $1.50.
In [10]:
print("Your name is {0} {1} {2}".format("James", "Tiberius", "Kirk"))
Your name is James Tiberius Kirk
In [12]:
print("Your name is {1} {2}, {0}".format("James", "Tiberius", "Kirk"))
Your name is Tiberius Kirk, James
In [14]:
# Lazy, always number your slots
print("Your name is {} {}, {}".format("James", "Tiberius", "Kirk"))
Your name is James Tiberius, Kirk
In [23]:
"Time left {0:>010}:{1:05.2f}".format(1, 37.374)
Out[23]:
'Time left 0000000001:37.37'