Python String Formatting
Strings Formatting
In this page, Python string formatting refers to the modification of text. Very often, strings and variables operate together, and formatting can help such processes function more efficiently.
This tutorial covers five different ways of formatting string in Python.
- f-strings (f”{}”)
- format method “format()”
- % operator
- concatenation (+)
- commas (,)
The list of formatting methods is sorted by effectiveness. The first and second methods, “f-strings” and “format” function, bypass many limitations that the rest of the formatting options have. Nevertheless, we recommend mastering all five ways, as each one of them can be useful in different situations.
F-strings (f”{}”)
The term f-strings refers to formatted strings literals. This method is very efficient, offering concise and neat way of formatting strings.
It uses the letter “f” outside the quotation marks and curly brackets”{}” to link external variables.
Please note that “f strings” work in Python version 3.6 or above.
name = "Peter" age = 20 print(f"The name is {name}. The age is {age}.") # Output: The name is Peter. The age is 20.
Format method “format()”
In the “format()” method, values are formatted through the function.
Similarly to “f-strings”, the relevant values go inside curly brackets.
The “format()” method assigns the values inside the functions brackets as arguments.
Python can declare such values through keyword arguments, indexes, and empty arguments (order is important).
Below is an example of all three options.
text = "The name is {name}. The age is {age}." print(text.format(name = "Peter", age = 20)) # Output: The name is Peter. The age is 20.
text = "The name is {0}. The age is {1}." print(text.format("John", 20)) # Output: The name is Peter. The age is 20.
text = "The name is {}. The age is {}." print(text.format("John", 20)) # Output: The name is Peter. The age is 20.
With this method, there are options of how to display the results through the use of format specifiers.
Below is an example of two format specifiers, using “:f” and “:%“. Both keyword and empty arguments apply.
Please note that keyword arguments always go last. In the case of a positional arguments following a keyword argument, Python produces a SyntaxError.
For more information on format specifiers here.
# .2 displays the output with only two decimal points # .0 displays the output without additional zeros text = "Watermelons cost £{:.2f}. This is {percent:.0%} percent of your daily budget." print(text.format(10, percent = 0.20)) # Output: Watermelons cost £10.00. This is 20% percent of your daily budget.
% operator
The percentage sign (%) can also format strings.
This method lacks some benefits of the newer ways of formatting strings.
Below are two examples using the percentage sign. The first uses “%s” for strings and the second “%d” for integers.
name = "Peter" age = 20 print("Hello %s " % name) print("You are %d " % age) # Output: Hello Peter # Output: You are 20
Concatenation (+)
The term concatenation refers to the combination of two or more strings.
Please note that concatenation can only combine strings text. In the case of a concatenation of a string and integer, Python produces a TypeError.
The following is an example of concatenating two strings.
name = "Peter" profession = "Carpenter" print("Hello, my name is " + name + "." + " And I am a " + profession + ".") # Output: Hello, my name is Peter. And I am a carpenter.
The example below displays a TypeError when Python tries to concatenate a string with an integer.
name = "Peter" age = 20 print("Hello, my name is " + name + "." + " And I am " + age + " years old.") # Output: TypeError: can only concatenate str (not "int") to str
Commas (,)
The use of commas can sometimes be useful with the “print()” statement.
With this method, Python does not output an error when combining strings text and numbers.
name = "Peter" age = 20 print("My name is", name, "and I am", age, "years old.") # Output: My name is Peter and I am 20 years old.