String Formatting in Python
Overview
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. A data scientist uses it to insert a title in a graph, show a message or error, or pass a statement to a function.
Introduction
String formatting is a way to insert a variable or another string in a predefined string. We can use various methods of string formatting in Python to manipulate strings.
We can use format specifiers like other programming languages to perform string formatting. We can also use the format() method and f-strings to manipulate strings in Python.
String Formatting in Python Using Format Specifiers
Like other programming languages, we can also use format specifiers to format strings in Python. Format specifiers are used with the % operator to perform string formatting.
The % operator, when invoked on a string, takes a variable or tuple of variables as input and places the variables in the specified format specifiers. Following is a table of the most commonly used format specifiers for different types of input variables.
To format a string in Python using format specifiers, We put the format specifier in the predefined string at the position where the variable is to be inserted. Then we insert the variable into the string using the % operator as follows –
Output –
We will specify the desired number of format specifiers to insert two or more variables into the string. Then we will pass a tuple of variables as input to the % operator. The % operator inserts the variables at the specified positions in a serial manner as follows.
Output –
Specifying variables with the correct data type for each format specifier is important. Otherwise, the TyperError exception is raised as follows.
Output –
Specifying the correct number of variables, equal to the number of format specifiers if we insert more than one variable into the string, is also essential. Inserting variables less than or greater than the number of format specifiers will again lead to the TypeError exception.
Output –
String Formatting in Python Using f-strings
Formatted strings or f-strings are string literals that can be used directly to insert variables into predefined strings. To format strings using f-strings, We only need to put variable names into placeholders made using curly braces “{ }”. The value of the variables defined in the placeholders is automatically updated by the python interpreter upon execution of the program as follows:
Output –
f-strings have an advantage over format specifiers: we don’t need to worry about data types of input variables. We also don’t need to worry about the order of input variables as we have to specify variable names directly into the placeholders.
String Formatting in Python Using the format() Method
Another way to format strings in Python is to use the format() method. In this method, first, we put placeholders in the string in which the variables are to be inserted. Then we invoke the format method on the string with variables that have to be inserted into the string as input arguments. After execution, the variables are serially placed in the placeholders as follows.
Output –
The format() method can be used with different types of arguments to perform string formatting in Python. Let us study the format() method in detail.
Syntax of the format() Method in Python
The syntax of the format() method in Python is as follows.
myString.format(val1, val2,…. ,valN)
Here, myString is the string containing placeholders for the variables to be inserted. val1, val2, val3 upto valN are the input variables to be inserted into myString.
In the format() method, if we pass input arguments greater than the number of placeholders in myString, Only the variables equal to the number of placeholders are inserted into the string, and the rest of the input arguments are ignored as follows.
Output –
If we pass variables less than the number of placeholders in myString, IndexError occurs as follows.
Output –
How Does the format() Method Work in Python?
The format() method can take input arguments in three ways. We will talk about them one by one.
Working with Default Arguments
The default way the format() method takes input is that we simply pass the variables as input arguments. When the method is invoked on a string, it places the values in the corresponding placeholders in the string one by one. In this case, we have to pass the input arguments in the same order they have to be inserted into the string.
For example, we can insert a string and an integer variable into a string using default arguments.
Output –
Working with Positional Arguments
Instead of empty placeholders, we can use the positions of the input arguments while inserting them into the string. We fill the index of input variables, in the placeholders, in the string, and during execution, the input arguments are inserted into the string according to their positions. In this method, we are not required to pass the input arguments in the same order they have to be inserted into the string. Instead, we can specify the placeholder where a particular variable will be inserted. It can be observed in the following example.
Output –
Working with Keyword Arguments
We can also use keyword arguments in the format() method for string formatting in Python. In this method, we define keywords in the placeholders and then pass the input variables as keyword arguments as follows. In this method, we are not required to pass the input arguments in the same order the keywords have been specified. This method gives us better flexibility to us. And we can use the variable by placing the keyword anywhere in the string, irrespective of the position at which it has been defined in the input. It can be observed in the following example.
Output –
Number Formatting Using Format() Method in Python
Using the format() method, we can perform format numbers differently. To simply display a signed or unsigned integer in a string, we can pass the variable as input to the format() method as follows:
Output –
Numbers can also be left, right, or center aligned using Python format() method.
For displaying a number with left alignment, we use the “:<n” symbol inside the placeholder in the format() method. Here n is the total length of the required output string. For example, if you have several lengths 4 (5 including the – sign) and have to pad it with spaces to make its length 10 while printing, you can do it as follows.
Output –
The period “.” in the output occurs after 5 space characters. It shows that when we align a number to the left with a certain length, the required number of spaces is padded to the number from the right side to achieve the output length.
For displaying a number with the right alignment, we use the “:>n” symbol inside the placeholder. Here n is the total length of the required output.
Output –
Here you can see that after aligning the number to the right, the required output length is achieved by adding spaces to the left side of the number.
To display a number with center alignment, we use the “:^n” symbol inside the placeholder. Here n is the total length of the required output.
Output –
In the output, you can see that the required number of spaces to achieve the output length is distributed on both sides of the number when we align the number in the center.
String Formatting Using the format() Method in Python
We can also perform different operations like truncating, padding, and alignment on the strings in Python using the format() method.
Alignment of Strings Using the format() Method in Python
For the alignment of strings, we use the same syntax we used for the alignment of numbers.
To left-align a string, we use the “:<n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
To right align a string, we use the “:>n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
To center align a string, we use the “:^n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
Truncating Strings Using the format() Method in Python
To truncate a string to a specific length, we use the symbol “:.n” inside the placeholder of the empty string at which the format() method is invoked. Then we pass the input string as the argument to the format() method as follows: Here, n is the required output length.
Output –
Padding Strings Using the format() Method in Python
We use the same syntax we used for alignment operation to perform padding on the strings. Alignment is a specific type of padding in which the padding character is the space character.
To pad strings with other characters, we can use the syntax as defined below. Here we assume that we have to pad the strings using the * character.
To pad a string on the left side with , we use the “:<n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
To pad a string on the right side, we use the “:*>n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
To pad a string keeping the input string in the center, we use the “:*^n” symbol inside the placeholder. Here n is the total length of the required output string.
Output –
Formatting Class Members Using the format() Method in Python
Like other strings, we can also format class members using the format() method in Python. For this, we just have to pass the class members to the format() method as input argument as follows:
Output –
Dynamic Formatting Using the format() Method in Python
Until now, we have used only those formatting types in which the output string size was fixed. To dynamically set the size of the output string, we can pass the size as input to the format() method. For this, we will use an extra placeholder for the size of the output string inside the placeholder for the input string.
To left-align a string, we use the “:<n” symbol inside the placeholder. Here “n” is the total length of the required output string. To dynamically set the size of the output string, we can insert a placeholder in place of “n” and pass the value “n” as input to the format() method as follows.
Output –
Similarly, we can perform other types of dynamic formatting using the format() method as follows.
Output –
When the specified output length is less than the input string length, the input string is not altered during the alignment and padding. In case of truncating, the output string is truncated to the required output length. This can be observed in the following example.
Output –
However, when the given output length is negative, ValueError will occur with a message “ValueError: Sign not allowed in string format specifier” as seen below.
Output –
Conclusion
- String formatting is also known as String interpolation.
- It is the process of inserting a custom string or variable in predefined text.
- We can format the strings in the following ways:
- with Format Specifiers
- using f-strings
- using format() string method
- The old-style formatting method uses the % operator and can be used with various data types.
- The new-style formatting method uses curly braces {} and can format strings with multiple variables.
- f-strings are a newer and simpler way of formatting strings that use the f prefix and allow for inline expressions.
- String formatting allows for customization of output and improves user experience.
Read More
- What is f string in python?
- How to convert int to string in Python?
- How to convert string to datetime in python?
- What are the string methods?