Python String Format
Python has three ways to format the string.
1. Use %
Operator
name = 'John'
age = 30
money = 10.72
print('Hello, %s. You are %d years old.' % (name, age))
# Output: "Hello, John. You are 30 years old."
We can set different formats. For example,
print("a: %2d, b: %5.2f" % (1, 05.333)) # a: 1, b: 5.33
print("%7.3o" % (25)) # 031 (octal value)
print("%10.3e" % (356.08977)) # 3.561e+02 (exponential value)
2. Use .format()
method
name = 'John'
age = 30
print('Hello, {}. You are {} years old.'.format(name, age))
# Output: "Hello, John. You are 30 years old."
We can also set more detailed formats in the curly bracket, including print orders, number formats, and keywords. For example,
print('{0} and {1}'.format('a', 'b')) # a and b
print('{1} and {0}'.format('a', 'b')) # b and a
print("a: {0:2d}, b: {1:8.2f}".format(12, 00.546)) # a: 12, b: 0.55
print("b: {1:3d}, a: {0:7.2f}".format(47.42, 11)) # b: 11, a: 47.42
print("a: {x:5d}, b: {y:8.2f}".format(x = 453, y = 59.058)) # a: 453, b: 59.06
3. Use F-string (Python >= 3.6)
name = 'John'
age = 30
print(f'Hello, {name}. You are {age} years old.')
# Output: "Hello, John. You are 30 years old."
F-string literals are the most concise and easy-to-read way to format strings. It also accepts formats like :8.2f
.