In Python string is a sequence of characters wrapped in single or double quotation marks.
Python comes with an in-built method of String class for string formatting. Python str.format()
method allows us to do string formatting and substitution operations.
Let's have a real-world example when you need string formatting.
Imagine you have a website which has many users these users are further divided into staff and regular users, Staff users have authority to access some private pages which regular user don't. So when a regular user "Jhon" hits those URL's we need to show a message to our user like,
Sorry Jhon, you are not allowed to access this page
We have to use string formatting to print Username along with the Error because it is not possible to hardcode the error for every user.
How to do String Formatting?
In Python string formatting works by putting placeholders which are nothing but a pair of curly braces{} in a string object, which are replaced by the arguments of the str.format() method, this can be better understood by the following example,
>>> print("I love {}.".format("Python"))
I love Python.
Here we created a string object with a placeholder defined by curly braces followed by the format method where we passed the argument "Python" which got concatenated with the string object.
These arguments inside format method can be anything integer, string, float or even variables.
Similarly, we can pass the user name as an argument to get the following output:
>>> print("Sorry, {} you are not allowed to access the page.".format("Jhon"))
Sorry Jhon, you are not allowed to access this page
We can also assign a string with a placeholder to a variable then call the variable with the format method along with the arguments like this,
>>> my_var = "I love {}"
>>> print(my_var.format("Django Central"))
I love Django Central
Using multiple placeholders
There are no limits on the number of placeholders a string can have, Placeholders will get replaced by the arguments in the order they are arranged.
Look at the below example,
>>> print(" I love {} and {}".format("python","django"))
I love python and django
In multiple substitutions, the arguments of format method are separated by a comma(,) and they replace the {} in the same order they are arrayed.
We can also assign values to a variable then call them inside format method like this:
>>> x = "Python"
>>> y = "Django"
>>> print("I love {} and {}".format(x,y))
I love Python and Django
Positional Arguments
Till now we have only used empty placeholders {}. However, we can also pass arguments within them.
We have already seen that, if we keep placeholders empty then Python will replace them with values present in the format method in arrayed order.
This default nature can be changed by passing the index of the argument inside the curly braces.
>>> print(" I love {1} and {0}".format("python","django"))
I love django and python
Here we passed the index of the arguments in the reverse order, so the first pair of curly braces gets substitute by the second argument and the second one by the first argument.
The values inside the format method are nothing but the tuple datatype, which can be called by the index numbers, keep in mind the index starts from 0.
If we try to call an index which doesn't exist, we will get an error like this,
>>> print(" I love {1} and {2}".format("python","django"))
IndexError: tuple index out of range
Keyword arguments
Keyword arguments are essentially variables storing some value which are passed into the placeholder as a parameter. Sometimes parameters are also referred as Keyword name.
>>> print(" I love {x} and {y}".format(x="Python",y="Django"))
I love Python and Django
Keyword arguments along with positional arguments can be used on a single String object
>>> print(" I love {0} and {y}".format("Python",y="Django"))
I love Python and Django
Specifying Type
Conversion of a Value using format method is also possible. Use the format code syntax {field_name:conversion}
, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.
Conversion code is the single character python code used in Python, which are
s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation
Let's convert an integer value to float,
>>> print("I am {} feet tall".format(5))
I am 5 feet tall
>>> print("I am {:f} feet tall".format(5))
I am 5.000000 feet tall
By adding :f
inside the curly braces we turned our integer to a float number. By default Python will put 6 digits after the decimal we can change that too;
>>> print("I am {:.2f} feet tall".format(5))
I am 5.00 feet tall
We limited the places after the decimal to 2 just by adding .2
inside the curly braces.
Add padding
As we can observe, Placeholders are getting replaced by the arguments. Meanwhile, we can also add padding around them. Padding is nothing but some extra space around the text.
>>> print(" I love {0:10} and {1:10}, Notice the extra padding?".format("python","django"))
I love python and django , Notice extra padding?
Here we added extra ten character padding inside the placeholders in order to get an extra 10 character space.
We can also modify the alignment of the values inside the string.
(<) will left- align the text and (>) will right-align the text and (^) will center the text. Pass these parameters just after the colon and before the padding like this:
>>> print(" I love {0:^20} and {1:^20}, Notice the alignment?".format("Python","Django"))
I love Python and Django , Notice the alignment?
But when should one use this padding property?
Well, Formatters are generally used to organize data in a readable way. This can be better understand by the following example,
for i in range(2, 12):
print(i, i*i, i*i*i)
This gave us the following output
2 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 72910 100 100011 121 1331
We are getiing our desired output but the data is not much appealing, we can add some padding to make our data more organized.
for i in range(2, 12):
print("{:^10d} {:^10d} {:^10d}".format(i, i*i, i*i*i))
This should give us the following output,
Now our data looks better rather say organized.
There are plenty of other things we can do with the format method like,
Dictionary keys can be used as arguments as well:
my_dict = {'key': 6, 'other_key': 7}
print("My other key is: {[other_key]}".format(my_dict))Output : "My other key is: 7"
Same applies to list and tuple indices:
my_list = ['zero', 'one', 'two']
print("2nd element is: {[2]}".format(my_list))
Output: "2nd element is: two"