There are multiple ways to format strings in Python:
%
-formatting:We can use the %
operator to format the string objects shown below:
word = "World!"
print("Hello, %s." % word)
Let’s try this formatting:
name = "Marry"print("Hello, %s." % name)
str.format()
:We can also call the built-in string format()
function for formatting strings like this:
word = "World!"
string = "Hello, {}.".format(word)
print(string)
Let’s try it.
name = "Marry!"string = "Hello, {}.".format(name)print(string)
Note: Both of the options given above are readable, but our code will become less legible and messy when we use longer strings. Another option is to format the
f
-strings in Python.
"Formatted string literals" are the string literals in which we use an f
at the beginning and curly braces {}
to enclose the expressions that will be replaced with other values.
word = "World!"
fstring = f"Hello, {word}."
Let’s try out this type of formatting:
name = "Marry"age = 18fstring = f"Hello, {name}. Are you {age} years old?"print(fstring)