EN
Python - format strings
0 points
In this article, we would like to show you how to format strings in Python.
Quick solution:
xxxxxxxxxx
1
color = "red"
2
text = "The apple is {}."
3
4
print(text.format(color)) # The apple is red.
In this example, to format the string we use format()
method that takes the passed arguments and puts them in the place of the placeholders {}
.
xxxxxxxxxx
1
name = "Tom"
2
age = 25
3
4
text = "This is my friend {}, he is {}."
5
6
print(text.format(name, age))
Output:
xxxxxxxxxx
1
This is my friend Tom, he is 25.
You can also specify the placeholders order by using numbered indexes ({0}
, {1}
) or named indexes ({name}
, {age}
).
xxxxxxxxxx
1
name = "Tom"
2
age = 25
3
4
text = "This is my friend {1}, he is {0}."
5
6
print(text.format(age, name))
or
xxxxxxxxxx
1
text = "This is my friend {name}, he is {age}."
2
3
print(text.format(name="Tom", age=25))
Output:
xxxxxxxxxx
1
This is my friend Tom, he is 25.