Python has a basic way of formatting strings like in other programming languages.
- The ‘%’ or modulus operator (percentage sign) is generally supported in many languages and so in Python.
- Besides, Python also has other ways of string formatting.
- In this tutorial, we will look at ‘%’ operator and string.format() function for string formatting in Python.
First Way: Using ‘%’ for string formatting
This is an old style that you might be familiar with if you have background with C language. Python also supports this but you may want using the newly available method for string formatting (explained in next section).
The example below shows how ‘%’ operator works:
#A demo of string formatting with % f_name = "Mike" l_name = "Anthony" formatted_str = 'The first name is %s and second name is %s' % (f_name, l_name) print (formatted_str)
The output:
In the code, you can see I used %s which represents a value as a string. This is followed by using the variable name in parenthesis in the same sequence as you would like to replace the %s with string variable values.
You may use various directives for formatting:
Directive | Description |
%s | %s is used for strings |
%d | %d for decimal integers |
%i | %i for integers |
%f | %f for float |
%x | %x for Hexadecimal integers |
%o | %o for octal integer |
%u | %u for unsigned integer |
%e | %e for float exponent |
Using integer and float along with string objects example
In this example, I also used %d for integer and %f for a float along with %s for string representation.
For that, I used three object variables that hold the Name, age, and salary of an employee (for the demo only):
#A demo of string formatting with % str_name = "Mike" age = 35 salary = 5000.00 formatted_str = 'Employee Name is %s, age is %i and salary is %1.2f!' % (str_name, age, salary) print (formatted_str)
The output of the above code is:
Using a list example
You may also use a list as shown in the example below:
amount_paid = [4000, 4000, 4500, 4500, 5000] emp_name = "Mike" emp_record = "Employee Name is %s. The paid amount are: %s" % (emp_name, amount_paid) print (emp_record)
The result:
Second way: Using string string.format method
The second and more usable way of formatting strings in Python is the str.format function which is part of the string class. The general syntax for using the str.format function is:
In this way of string formatting, we use placeholders in the string object. The placeholder is in the form of curly braces i.e. {}.
First, have a look at this simple example of the str.format method and I will explain later how it works:
#A demo of string formatting with str.format() function fmt = "String Format Tutorial" print("Python {} Tutorial.".format("Formatting")) print("The {}.".format(fmt))
The output:
In the example above, you can see that string formatting is done in two ways.
First, a value is given in the format function. The other print function uses a variable for the substitution of the place-holder.
An example of using multiple pairs of curly braces
You may also use multiple placeholders for formatting strings i.e. pairs of curly braces.
#A demo str.format with multiple placeholders print("Demo with {} {}." .format("multiple", "place-holders"))
The result:
So, you may use more than one value or variable in the format function that are separated by a comma.
The substitution is done in the same order as per place-holder in the calling string, however, you may also provide a position as shown in the example below.
The example of using positional arguments
The demo below shows how to use positional arguments in the string format function. In the place-holder, i.e. within the curly braces, you may provide the number according to the argument in the format function.
See an example below and I will explain more:
#A demo of str.format with positional arguments emp_name = "Sarah" emp_sal = 5000 print("Employee Name is {0}, Salary is {1}.".format("Mike", 4500)) print("Employee Name is {1}, Salary is {0}.".format(emp_sal, emp_name))
The output:
Employee Name is Mike, Salary is 4500.
Employee Name is Sarah, Salary is 5000.
A few points to learn from the above example:
- We used values and object variables in the format function as arguments.
- In the first print function, I used 0 and 1 and the result is displayed in the same order as I sent arguments. That is, Mike and 4500 in the output formatted string.
- In the second print function, the order is 1 and 0. The first argument in the format function is emp_sal which is equal to 0 and emp_name = 1. So, in the output string, the emp_name variable value is replaced with {1} and salary by {0}.
- In that way, you may control the usage of argument position in the formatted string.
Using keyword argument example
Not only you may provide the numbers in the curly braces but you may refer the arguments by keywords as well – thus making code cleaner. Have a look at the code and output below:
#A demo of str.format with keyword arguments emp_name = "Haynes" emp_sal = 7500 #using values with keywords print("Employee Name is {emp}, Salary is {sal}.".format(emp = "Michelle", sal = 6500)) #Using variables with keywords print("Employee Name is {emp}, Salary is {sal}.".format(sal = emp_sal, emp = emp_name))
The output:
Employee Name is Michelle, Salary is 6500.
Employee Name is Haynes, Salary is 7500.
There, you can see I used {emp} and {sal} to refer to these keywords in the format function. Inside the format function, I used values as well as variables with keywords.
You may also notice that the order is not important as calling in the placeholder as the sequence of the format function arguments.
An example of formatting date with string.format
You may format numbers like integers, float, etc. as using the string.format function.
I will show you in the examples below; first, have a look at using various date directives for formatting dates using format function.
import datetime current_date = datetime.datetime.today() dt_fmt1 = '{:%a, %b %d %Y}'.format(current_date) dt_fmt2 = '{:%A, %B %d %Y}'.format(current_date) dt_fmt3 = '{:%m/%d/%Y}'.format(current_date) dt_fmt4 = '{:%d-%m-%Y}'.format(current_date) dt_fmt5 = '{:%m/%d/%y %H:%M %S}'.format(current_date) dt_fmt6 = '{:%m/%d/%y %I:%M %S %p}'.format(current_date) print(dt_fmt1) print(dt_fmt2) print(dt_fmt3) print(dt_fmt4) print(dt_fmt5) print(dt_fmt6)
The output as I executed this code:
In the example, I used datetime module and get the current date by datetime’s today() function. This value is used in the format function with various date directives for formatting.
How to perform formatting for numbers using format function?
By using format specifiers for numbers, you may also format numbers by using the format() function. A list of specifiers used with % operator is given in the above section. As using the format() function, the specifier is used without ‘%’ operator.
A few commonly used number specifiers/conversion characters are:
Specifiers/Conversion Character | Description |
d | d is used for decimal integers |
b | b for binary format |
o | o for octal format |
x | x is for the hexadecimal format (lowercase letters) |
X | X for hexadecimal (uppercase letters) |
f | f for floating point number which is fixed. The default is 6 precision. |
c | c for character |
e | e is for exponent notation |
The syntax for using a specifier in the format function is as follows:
An example of int and float conversion
This example uses int and float numbers in the place-holder:
print("Using decimal number = {:d}".format(5000)) print("Float Number = {:f}".format(5000))
The output:
Using decimal number = 5000
Float Number = 5000.000000
A float with 2 precision
In above example, you can see the float number is converted with 6 precision which is the default value. For changing the precision, you may do this as follows:
print("Float Number with 2 precision = {:.2f}".format(5555.475845)) print("Float Number with 3 precision = {:.3f}".format(5555.784784))
The result:
Float Number with 2 precision = 5555.48
Float Number with 3 precision = 5555.785