String formatting is an essential part of Python programming for web development, data analysis, machine learning, and more.
In earlier posts, we discussed set up Python development environment, including installing the Windows Terminal, adding Anaconda Prompt on the Windows terminal, adding it on the Windows right-click menu, adding Anaconda PowerShell Prompt on the Windows terminal, or adding it on the Windows right-click menu. Besides, more recently, I introduced an Easy Way to Add Anaconda PowerShell Prompt on the Windows Terminal.
In this post, we will discuss on Python string formatting methods, and 5 essential string formatting methods in Python will be displayed with concrete examples.
score = 95
print('The average score of Group A:', score)
The average score of Group A: 95
(2) More than one variable
group = 'Group A'
score = 95
print('The average score of', group, ':', score)
The average score of Group A : 95
(3) A list
score_list = [95,96,86,55]
print("The average scores of Group A, Group B, Group C and Group D are", score_list)
The average scores of Group A, Group B, Group C and Group D are [95, 96, 86, 55]
2. Concatenation method
Similarly, we can use ‘+’ sign to concatenate string and variables, like print('string+ '' + variable)
. Let’s see the same example as above. This method can only be used to concatenate string variables. But we can change a numeric variable into a string, or use the comma method.
(1) One variable
score = 95
print('The average score of Group A: ' + str(score))
The average score of Group A: 95
(2) More than one variable
group = 'Group A'
score = 95
print('The average score of' + group + ': ' + str(score))
The average score of Group A: 95
# or
print('The average score of' + group + ':', score)
The average score of Group A: 95
(3) A list
score_list = [95,96,86,55]
print("The average scores of Group A, Group B, Group C and Group D are " + str(score_list))
The average scores of Group A, Group B, Group C and Group D are [95, 96, 86, 55]
3. % formatting
This is a comparatively older method of string formatting in Python, which uses the % operator. The %s
marker inserts a string, the %d
marker inserts an integer, and the %f
marker inserts a float. Let’s see some examples.
(1) One variable
name = 'Mike'
print('Hello, %s!'%name)
Hello, Mike!
%s
.(2) More than one variable
name = 'Jack'
age = 20
print('%s is %d years old.' %(name,age))
Jack is 20 years old.
%s
and %d
, respectively.(3) A list
alist = [5,1,8]
print("A list: %s" %alist)
A list: [5, 1, 8]
(4) Format the number value
We usually use Python to make calculations, where the floating numbers are usual. Let’s see how to format float decimal place with certain decimal places, such as 0.2, 0.22, …
x = 1
y = 3
z = x/y
print('The result of %d divided by %d is %f.'%(x,y,z))
print('The result of %d divided by %d with one decimal '\
'place is %.1f.'%(x,y,z))
print('The result of %d divived by %d with '\
'two decimal places is %.2f.'%(x,y,z))
print('The result of %d divided by %d with '\
'three decimal places is %.3f.'%(x,y,z))
The result of 1 divided by 3 is 0.333333. The result of 1 divided by 3 with one decimal place is 0.3. The result of 1 divived by 3 with two decimal places is 0.33. The result of 1 divided by 3 with three decimal places is 0.333.
4. Curly brace string formatting
The advantage of this method is that you can insert more than one values using curly brace, and the values can be numbers and other Python objects.
(1) Insert a string and number
name = 'Jack'
age = 20
print ('{} is {} years old.'.format(name, age))
Jack is 20 years old.
(2) Insert a complex data type
We can easily insert a complex data types, such as list, tuple, etc.
alist = [5,1,8]
print("A list: {}.".format(alist))
A list: [5, 1, 8].
(3) Format the number value
Let’s see the same example to display how to format float decimal places.
x = 1
y = 3
z = x/y
print('The result of {} dived by {} is {}.'.format(x,y,z))
print('The result of {} dived by {} with one decimal'\
'place is {:.1f}.'.format(x,y,z))
print('The result of {} dived by {} with'\
'two decimal places is {:.2f}.'.format(x,y,z))
print('The result of {} dived by {} with'\
'three decimal places is {:.3f}.'.format(x,y,z))
The result of 1 dived by 3 is 0.3333333333333333. The result of 1 dived by 3 with one decimal place is 0.3. The result of 1 dived by 3 with two decimal places is 0.33. The result of 1 dived by 3 with three decimal places is 0.333.
5. f-string method
This is a comparatively new method, which is only after Python >= version 3.6. An f
prefix at the beginning of the string tells Python to insert any currently valid variables into the string. It is the most convenient and practical string formatting method in Python at the moment. We cannot cover all the functions of this method, so here we only take some examples to compare with the above methods.
(1) One variable
name = 'Jack'
print(f'Hello, {name}.')
Hello, Jack.
(2) More than one variable
name = 'Jack'
age = 20
print(f'{name} is {age} years old.')
Jack is 20 years old.
(3) f-string list
alist = [5,1,8]
print(f"A list: {alist}")
A list: [5, 1, 8]
(4) Formatting floats
x = 1
y = 3
z = x/y
print(f'{x} is dived by {y} is {z}.')
print(f'{x} is dived by {y} is {z:.1f}.')
print(f'{x} is dived by {y} is {z:.2f}.')
print(f'{x} is dived by {y} is {z:.3f}.')
print(f'{x} is dived by {y} is {z:.4f}.')
1 is dived by 3 is 0.3333333333333333. 1 is dived by 3 is 0.3. 1 is dived by 3 is 0.33. 1 is dived by 3 is 0.333. 1 is dived by 3 is 0.3333.
(5) f-string Dictionaries
Let’s see a dictionary example as follows.
fruit = {
'name': 'Apple',
'price': '3.0'
}
print(f"{fruit['name']} is ${fruit['price']}")
Apple is $3.0
It can also insert a calculation express. For example:
apple_amount = 5 # kg
cost = 3.0 # Dollar per kg
print(f'Total cost of the apple is ${apple_amount * cost}.')
Total cost of the apple is $15.0.
(7) multiline f-string
Another convenient thing of this method is that we can insert a multi-line string.
name = 'Jack Smith'
age = 25
occupation = 'Professor'
file = (
f'Name: {name}\n'
f'Age: {age}\n'
f'Occupation: {occupation}'
)
print(file)
Name: Jack Smith Age: 25 Occupation: Professor
(8) f-string calling function
Besides, we can also call a function directly.
def additor(x, y):
return x + y
a = 5
b = 7
print(f'Sum of {a} and {b} is {additor(a, b)}')
Sum of 5 and 7 is 12
(9) f-string objects
Besides the function, it can also be used in the class objects, but the objects must have either str() or repr() magic functions defined in the class.
class User:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
def __repr__(self):
return f"{self.name} is a {self.occupation}"
u = User('Jack Lee', 'Professor')
print(f'{u}')
Jack Lee is a Professor
(10) f-string format width
The value may be filled with spaces or other characters if the value is shorter than the specified width
In the following example, it prints three columns, and each column has a predefined width. The first column uses 0 to fill shorter values.
for x in range(0, 10):
print(f'{x:02} {x*x:3} {x*x*x:4}')
00 0 0 01 1 1 02 4 8 03 9 27 04 16 64 05 25 125 06 36 216 07 49 343 08 64 512 09 81 729
s1 = '1'
s2 = '12'
s3 = '123'
s4 = '1234'
s4 = '12345'
print(f'{s1:>5}')
print(f'{s2:>5}')
print(f'{s3:>5}')
print(f'{s4:>5}')
1 12 123 12345