- PyFormat Using % and .format() for great good!
- Table of Contents:
- Basic formatting
- Old
- String Formatting in Python
- Introduction
- String Formatting in Python Using Format Specifiers
- String formatting in Python using f-strings
- String Formatting in Python Using the format() Method
- Syntax of the format() method in Python
- How Does the format() Method Work in Python?
- Working with Default Arguments
- Working with Positional Arguments
- Working with Keyword Arguments
- Number Formatting Using Format() Method in Python
- String Formatting Using the format() Method in Python
- Alignment of Strings Using the format() Method in Python
- Truncating Strings Using the format() Method in Python
- Padding Strings using the format() method in Python
- Formatting Class Members Using the format() Method in Python
- Dynamic Formatting Using the format() method in Python
- Conclusion
- Read More:
PyFormat Using % and .format() for great good!
Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.
All examples on this page work out of the box with with Python 2.7, 3.2, 3.3, 3.4, and 3.5 without requiring any additional libraries.
Further details about these two formatting methods can be found in the official Python documentation:
If you want to contribute more examples, feel free to create a pull-request on Github!
Table of Contents:
- Basic formatting
- Value conversion
- Padding and aligning strings
- Truncating long strings
- Combining truncating and padding
- Numbers
- Padding numbers
- Signed numbers
- Named placeholders
- Getitem and Getattr
- Datetime
- Parametrized formats
- Custom objects
Basic formatting
Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate.
Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.
Old
String Formatting in Python
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 –
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.
Specifying variables with the correct data type for each format specifier is important. Otherwise, the TyperError exception is raised as follows.
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.
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:
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.
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.
If we pass variables less than the number of placeholders in myString, IndexError occurs as follows.
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.
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.
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.
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:
Numbers can also be left, right, or centre aligned using python format() method.
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.
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 centre alignment, we use the “:^n” symbol inside the placeholder. Here n is the total length of the required 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 right align a string, we use the “:>n” symbol inside the placeholder. Here n is the total length of the required output string.
To center align a string, we use the “:^n” symbol inside the placeholder. Here n is the total length of the required output string.
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.
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 right side, we use the “:*>n” symbol inside the placeholder. Here n is the total length of the required output string.
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.
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:
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.
Similarly, we can perform other types of dynamic formatting using the format() method as follows.
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.
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.
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
Read More: