Languages
[Edit]
EN

Python - format strings

0 points
Created by:
Khloe-Kaiser
578

In this article, we would like to show you how to format strings in Python.

Quick solution:

color = "red"
text = "The apple is {}."

print(text.format(color))  # The apple is red.

 

Practical examples

Example 1

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 {}.

name = "Tom"
age = 25

text = "This is my friend {}, he is {}."

print(text.format(name, age))

Output:

This is my friend Tom, he is 25.

Example 2

You can also specify the placeholders order by using numbered indexes ({0}, {1}) or named indexes ({name}, {age}).

name = "Tom"
age = 25

text = "This is my friend {1}, he is {0}."

print(text.format(age, name))

or

text = "This is my friend {name}, he is {age}."

print(text.format(name="Tom", age=25))

Output:

This is my friend Tom, he is 25.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - string (popular problems)

Python - format strings
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join