Python String format()

Python String Format()

This is a detailed tutorial on the Python String format() method. Learn to do multiple substitutions and value formatting using this python string function.

Python String format() Method

The format() method is one of the Python Methods used for String Formatting. By string formatting, we mean to substitute different values at multiple different instances in the string in a structured way. This method is very helpful in case you have multiple values to substitute in a string which otherwise would have taken a lot of effort with conventional methods like concatenation.

Especially, when you have to substitute values in a string that do not directly belong to the Python String (class <str>) data type then you also have to convert each of such values into a string first using the str constructor method and then have to concatenate the value into the string. And the coding efforts in such cases are tremendous!

The string format() method can be used to substitute a single value or multiple values as well.

Syntax

The return type of this function is the formatted string. You must use the symbol {} in case of a single value formatting wherever you want to substitute the value and the value itself has to be written as an argument inside the format method applied on that particular string.

In case you want to substitute multiple values, the multiple {} symbols are used and to fill those symbols in the string, the multiple values are written as an argument inside the method format() separated by commas. For multiple values python string formatting, there is also another way to handle the approach and that we’ll discuss later in this article.

Single Value Formatting

The format() method follows an innovative approach, in which we make use of the symbol {}, (Curley Braces) to substitute values in the string and then we specify the variables or values to replace that symbol in the string by passing them as the arguments to the method format().

Example. In the following example, I’m substituting my name as a value in the string using the Python String format() method.

I’ve passed my name as a string argument to the format() method that I applied on the string in which I’ve to substitute the value at the place of the {} symbol.

Python String Format() Example

You can clearly see in the output that instead of the {} symbol, we got our desired value formatted in the string. As I mentioned earlier, the string method format() also makes it easier to substitute any kind of data type into the string directly without the need of explicitly doing the type conversion.

Example. It demonstrates the formatting of the string with integer data type and an iterable list data type.

Python String Format() Substitute Values Of Any Data Type Example

Formatting Multiple Values

Till now, we’ve learned the use of the method format() to substitute a single value of any data type into any existing string. But usually, we require to substitute multiple values in the strings.

Example. The following code illustrates the use of the method format() to substitute multiple values, both belonging to different data types, one string, and one integer.

In the above code, you can see I’ve used the {} symbol two times in the string and formatting with the method format() to substitute the two values in the same order as they are written as arguments to this method. You can see in the output that the order in which the arguments are being replaced by the {} symbol in the string is exactly the same.

Python String Formatting Multiple Substitutions Example

Now, the order thing can not be used for most of the practical applications. The one value may be required to be substituted in the string multiple times and at different and random instances having no co-relation with the other values that also have to be substituted in the same string formatting. Therefore, there’s another concept of string formatting discussed in the next section of this article.

But before that let’s talk about a common error that is being raised by the format() method in case the number of {} symbols in the string is more than the number of provided arguments in the method.

IndexError

Example. The following example illustrates that when we’re using more than the required arguments the format() method does not raise any error, but if we’ll have lesser arguments than the required one, then it raises IndexError.

In the first case, we’re adding one more argument than the required number of arguments, you can see the string formatting is being done properly without causing any errors.

But as in the second case, when we’re having only one argument passed but actually two arguments are required to be passed for the substitution of the values at two places, the IndexError is being raised by this method. You can handle any kind of such runtime errors using Try Except in python.

Python String Format() Method IndexError Example

Positional String Formatting

Instead of using empty curly braces, you can specify the indexes inside these braces that will reflect the index as per the order of argument values inside the parenthesis of the format() method. For example, {0} will point to the value of the first argument as the indexing starts from 0. This way you can randomly substitute values in any string by specifying the indexes inside the curly braces.

Example. The following python code makes use of the Python string format() method for multiple values substitution using the indexes of the arguments of the method.

Python String Positional Formatting Using Format() Method Example

Keyworded String Formatting

In python functions, you can provide keyworded arguments, therefore these keywords can also be used to substitute values in the strings. You have to specify the keyworded arguments to the method format() and in the string on which you will apply this method, you just use the Curley braces with the keywords written inside them. {keyword}

Example. The following python code does the string formatting using the keyworded approach.

You can observe that we’re doing exactly the formatting for the same output, it’s just that we’re directly using the keywords for the value instead of using their positions.

Python String Keyworded Arguments String Formatting Using Format() Method Example

Note. KeyError will be raised in case you will try to substitute a keyword that you have not specified as an argument with value in the format method applied on the string.

Type Conversion Substitution Formatting

There might be cases when you may not require to specify the data type as it is in the string but you might be wanted to first convert it into a more useful data type and then substituting its value in the string. Without string formatting, you may do it by doing explicit type conversion and then concatenating the resultant value in the string.

Well, with the string format() method, you need not bother much and need not do the explicit type conversion as there’s another easy way to do the same. There’s another notation, and it is {position/keyword:conversionSymbol}.

The format function makes use of some symbols that can be used for implicit type conversions without using the constructor methods for every different type of conversion. In the specified format, the conversionSymbol is unique for each different inbuilt python data type and this is the data type that will be used to substitute the value in the string.

These symbols are given below in the tabular form.

Symbol Data Type
s String
d Decimal Integers (Base 10)
f Floating Points
c Characters
b Binary
o Octal
x Lowercase Hexadecimal Letters
X Uppercase Hexadecimal Letters
e Exponential Notation

Example. Observe the following code along with its output carefully to understanding how you can do type conversion within the format() method.

Notice the difference between the output of the variables line1 and line2. In the first case, we’re using the symbol f to convert the integer value into a floating-point value in the string. This way you can do type conversions in other data types also, just make sure the involved literals are valid.

Python String Formatting Type Conversions Example

Note. If the literals are invalid for specified symbol type conversion, the ValueError will be raised by this method.

You can also make use of these symbols along with numerical values that specify the number of positions for the output. For example, in case you want to specify the decimal values upto a certain accuracy, you can make use of this concept to display only the specified number of points values. The following code illustrates the same.

Python String Formatting Type Conversion Advanced Example

Alignment and Padding in String Formatting

With the help of alignment symbols and padding numbers, the different types of alignments, left, right or center and different paddings and spaces can be substituted along with the values substitutions using the python string format() method.

The symbols that are used for alignment purposes are given below.

Symbol Alignment
< Left Align
> Right Align
^ Center Align

On the other hand side, the numbers are used to specify that much amount of space or padding.

Example. Observer each case explained in the following code to understand how you can specify the alignment and padding for the values that you want to substitute in the python strings for better formatting.

Python Padding & Alignment Using Format() Method Example

You need to play with the format() method with different padding values and the alignment options to have a great understanding of Python String formatting.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *