string-format-method
String Format Method

The Python string format() method is used to format and insert a value(s) at a specified place in a string template. This means you can able to substitute parts of a string with new values from other variables, or expressions when using the string format method.

The format() method uses placeholders inside the string to indicate where values should be inserted and ways to format, this includes the formatting instructions that tend to modify the ways our values are displayed on the screen. The method finally returns the formatted string as a result.

We use curly brackets {} to specify the placeholders inside the string. The following subsections describe several ways we can specify or use the placeholders while our next sections discussed the ways we can format our results when using the format() method. The first choice of specifying the placeholders is to use an Empty placeholder, and the second and third are Named and Number placeholders respectively.

Empty Placeholder

In Python’s format() method, an Empty Placeholder is used to indicate the location where values can be inserted. Therefore we insert an empty placeholder inside a string and such placeholder is denoted by using a pair of curly braces: {}.

Example: Use an Empty Placeholder when using the string format() method.


# Empty Placeholder
var_str = "My favorite programing language is : {}. I have {} years of experience. "
var_lan= "Python"
var_exp = 7

print(var_str.format(var_lan,var_exp))
print(var_str.format("Java",8))

Output:


My favorite programing language is : Python. I have 7 years of experience. 
My favorite programing language is : Java. I have 8 years of experience.

Note: When using the Empty Placeholder, the order in which arguments are passed to the method corresponds to the order in which the placeholders appear in the string. This means, the order matters, and for instance, if we pass the first argument 7 it will be inserted into the first empty placeholder {} in the string, and if we pass "Java" to the second argument, it will be inserted into the second empty placeholder {}. Check the following examples for more understanding.

Example: The order matters when using the Empty Placeholder with the string format() method.


# Empty Placeholder
var_str = "My favorite programing language is : {}. I have {} years of experience."
var_lan= "Python"
var_exp = 7

print(var_str.format(var_exp, var_lan))

var_str = "My favorite programing language is : {}. I have {} years of experience. {}"

print(var_str.format(True,5,"Java"))

Output:


My favorite programing language is : 7. I have Python years of experience.
My favorite programing language is : True. I have 5 years of experience. Java

Over-specifying the Number of Arguments Passed to the format() Method using Empty Placeholders

Although it is not a good practice, Python allows us to over-specify the number of arguments passed to the format() method when using Empty Placeholders. This means we can pass more arguments than required. But we only recommend to only pass the required number of arguments that match the number of empty placeholders in the string. The following example shows how to do that.

Example: Over-specifying the number of arguments passed to the format() method in Empty Placeholders.


# Over Specifying arguments on Empty Placeholders
var_str = "My favorite number is : {}, I have {} US Dollar and {} cents. "
var_num= 8
var_dollar = 7
var_cent = 0.8

print(var_str.format(var_num,var_dollar,var_cent,8))
print(var_str.format(9,8,6,9))

Output:


My favorite number is : 8, I have 7 US Dollar and 0.8 cents. 
My favorite number is : 9, I have 8 US Dollar and 6 cents. 

Under-specifying the Number of Arguments Passed to the format() Method using Empty Placeholders

Under-specifying the number of arguments passed to the format() method when using the Empty Placeholders is not allowed in Python and it will trigger an error (IndexError) if you do so.

This behavior (under-specifying) happens when you have specified more empty placeholders in the string than arguments passed to the format() method. Python will not ignore this and might show an error saying something like this “tuple index out of range” or like this: “Replacement index 2 out of range for positional args tuple”.

Example: Under-specifying the number of arguments passed to the format() method in Empty Placeholders.


# Under_Specifying arguments on Empty Placeholders
var_str = "My favorite number is : {}, I have {} US Dollar and {} cents. "
var_num= 8
var_dollar = 7
var_cent = 0.8

print(var_str.format(var_num,var_dollar))
print(var_str.format(9,8))

Output:


Traceback (most recent call last):
  File "/Users/format_method.py", line 37, in <module>
    print(var_str.format(var_num,var_dollar))
IndexError: Replacement index 2 out of range for positional args tuple

Named Placeholder

In Python’s format() method, a Named Placeholder (also called named indexes) is a placeholder used to indicate the location where values can be inserted. This means we place a name as an argument inside the curly braces, for example: {name}.

Example: Use Named Placeholder when using the string format() method.


# Named Placeholder
var_str = "My favorite programing language is : {language}. I have {experience} years of experience. "
var_lan= "Python"
var_exp = 7

print(var_str.format(language = var_lan, experience = var_exp))
print(var_str.format(language = "C++", experience = 9))
print(var_str.format(experience = 3, language = "PHP"))

Output:


My favorite programing language is : Python. I have 7 years of experience. 
My favorite programing language is : C++. I have 9 years of experience. 
My favorite programing language is : PHP. I have 3 years of experience.

Note: Unlike the Empty Placeholders, the order of the arguments does not matter when using the Named Placeholders. According to the above example, if you want you can first pass the number of experiences to the experience placeholder, then the favorite language to the language placeholder.

Over-specifying the Number of Arguments Passed to the format() Method using Named Placeholders

Python does not allow you to over-specify the number of arguments passed to the format() method when using the Named Placeholders. This means we cannot pass more arguments than required. Although it is not a good practice and leads SyntaxError. Thus, Python only accepts when the number of named placeholders in the string matches the number of arguments passed to the format() method. The following example demonstrates such a scenario.

Example: Over-specifying the number of arguments passed to the format() method in Named Placeholders.


# Over-specify the Number of Arguments Passed to the format() Method in Named Placeholders
var_str = "Python is {int_num} easy to learn {float_num} and easy to understand {bool_num} "
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(int_num = var_int, float_num = var_float, bool_num = var_bool, 4))
print(var_str.format(int_num = 87, float_num = 8.90, bool_num = False, 89,48))

Output:


 File "/Users/format_method.py", line 64
    print(var_str.format(int_num = var_int, float_num = var_float, bool_num = var_bool, 4))
                                                                                         ^
SyntaxError: positional argument follows keyword argument 

Example: Repeating some of the placeholder’s name while we over-specifying the number of arguments passed to the format() method in Named Placeholders.


# Over-specify the Number of Arguments Passed to the format() Method in Named Placeholders
var_str = "Python is {int_num} easy to learn {float_num} and easy to understand {bool_num} "
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(int_num = var_int, float_num = var_float, bool_num = var_bool, float_num = 8.90))
print(var_str.format(int_num = 87, float_num = 8.90, bool_num = False, float_num = 8.90, bool_num = False,))

Output:


  File "/Users/format_method.py", line 64
    print(var_str.format(int_num = var_int, float_num = var_float, bool_num = var_bool, float_num = 8.90))
                                                                                        ^^^^^^^^^^^^^^^^
SyntaxError: keyword argument repeated: float_num 

Under-specifying the Number of Arguments Passed to the format() Method using Named Placeholders

Under-specifying the number of arguments passed to the format() method using named placeholders is not allowed in Python and it will trigger an error if you do so.

The under-specifying happens when you pass fewer arguments to the format() method than required by the string. This also means that the number of placeholders in the string is more than the number of arguments passed in the format() method. Or we can also say when some named placeholders are not given a corresponding argument, Python will not ignore this and will result in an error (KeyError).

Example: Under-specifying the number of arguments passed to the format() method in Named Placeholders.


# Under-specify the Number of Arguments Passed to the format() Method using Named Placeholders
var_str = "Python is {int_num} easy to learn {float_num} and easy to understand {bool_num} "
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(int_num = var_int,float_num = 8.90))
print(var_str.format(int_num = 87, float_num = 8.90))

Output:


Traceback (most recent call last):
  File "/Users/format_method.py", line 80, in <module>
    print(var_str.format(int_num=var_int, float_num=var_float))
KeyError: 'bool_num'

Numbered Placeholder

In Python’s format() method, a Numbered Placeholder (also called numbered indexes) is a placeholder used to indicate the location where values can be inserted. This means we place a number (or index number) as an argument inside the curly braces, for example: {0} or {1}.

Example: Use Numbered Placeholder (or index placeholder/numbered indexes) when using the string format() method.


# Numbered Placeholder (index placeholder/numbered indexes)
var_str = "This is int {0} this is float {1} this is bool {2} this is string {3}"
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(var_int, var_float, var_bool,"Amazing"))

Output:


This is int 90 this is float 89.67 this is bool True this is string Amazing

Order of the Arguments Matter When using the Numbered Placeholders

Unlike the Named Placeholders, the order of the arguments matters when using the Numbered Placeholders. The first argument will be formatted into the first numbered placeholder (the one with {0} index), the second argument will be formatted into the second placeholder (the one with {1} index), and so on.

But the order of the placeholders inside the string does not matter, what matters is the argument to be passed. See the following example for more clear understanding. Python will match the first argument to the first index which is {0} and the second argument passed will be matched to the second index which is {1} and so on.

Example: The order matters when using the Numbered Placeholder with the string format() method.


# The order of the Numbered Placeholder (index placeholder/numbered indexes)
var_str = "This is int {1} this is float {0} this is bool {3} this is string {2}"
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(var_int, var_float, var_bool,"Amazing"))

Output:


This is int 89.67 this is float 90 this is bool Amazing this is string True

Specifying all the Indices in Sequential Order in Numbered Placeholders

It is also very import to not to skip the sequence of the index numbers when specifying the Numbered Placeholders. Therefore it is compulsory to specify all the indices in sequential order. For example, index numbers start from 0 to n (any non-negative number), this means you must specify your numbered placeholders like this: {0}...{1}...{2}...{3} and so on. But not this way {0}...{2}...{3}...{4}. This skips the second index which is {1} and Python triggers an error (IndexError).

Example: The sequence of the index numbers matters when using the Numbered Placeholder with the string format() method.


# Do not skip index of the Numbered Placeholder (index placeholder/numbered indexes)
var_str = "This is int {1} this is float {4} this is bool {3} this is string {2}"
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(var_int, var_float, var_bool,"Amazing"))

Output:


Traceback (most recent call last):
  File "/Users/format_method.py", line 99, in <module>
    print(var_str.format(var_int, var_float, var_bool,"Amazing"))
IndexError: Replacement index 4 out of range for positional args tuple

Over-specifying the Number of Arguments Passed to the format() Method using Numbered Placeholders

Python does allows you to over-specify the number of arguments passed to the format() method when using the Numbered Placeholders (numbered indexes). This means, passing more arguments to the format() method than are required to fill in all the numbered placeholders in the string.

Over-specifying is not a good practice and should be avoided as it leads to confusion and loss of information. However, Python can accept when the number of arguments passed in the format() method is more than the number of placeholders specified in the string. The following demonstrates such a scenario.

Example: Over-specifying the number of arguments passed to the format() method in Numbered Placeholders.


# Over-specifying the Number of Arguments Passed to the format() Method using Numbered Placeholders
var_str = "Python is {0} easy to learn {1} and easy to understand {2} {3}"
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(var_int, var_float, var_bool, 8.90, "Over=specifying", "Is allowed"))

Output:


Python is 90 easy to learn 89.67 and easy to understand True 8.9

Under-specifying the Number of Arguments Passed to the format() Method using Numbered Placeholders

Python does not allow you to under-specify the number of arguments passed to the format() method when using the Numbered Placeholders (numbered indexes). This means, passing fewer arguments to the format() method than required to fill in all the numbered placeholders in the string.

Under-specifying is not allowed and Python cannot accept when the number of arguments passed in the format() method is less than the number of placeholders (numbered indexes) specified in the string. The following demonstrates such a situation.

Example: Under-specifying the number of arguments passed to the format() method in Numbered Placeholders.


# Under-specifying the Number of Arguments Passed to the format() Method using Numbered Placeholders
var_str = "Python is {0} easy to learn {1} and easy to understand {2} {3}"
var_int = 90
var_float = 89.67
var_bool = True

print(var_str.format(var_int, var_float, var_bool))

Output:


Traceback (most recent call last):
  File "/Users/format_method.py", line 115, in <module>
    print(var_str.format(var_int, var_float, var_bool))
IndexError: Replacement index 3 out of range for positional args tuple

The above code has resulted in an IndexError, which indicates that we have specified four named placeholders in the string while we specified only three arguments in the format() method. However, this violates the condition which says the number of numbered placeholders in the string must match the number of arguments passed to the format() method. 

Format Results Inside Placeholders

String formatting refers to the process of presenting data or string values in a desired format. In Python, when using the placeholders in a string and format() method we can able to format or control the ways the data is displayed using several formatting types.

In the following section, we group the different formatting types based on their relevance:

Number Formatting

The number formatting contains several format specifier that determines how the specified number should be displayed or formatted when using the string format() method. This method allows us to format numbers in a variety of ways. For example, we format numbers by including a placeholder in the string using curly braces {} and specify a format specifier after a colon :. These are the types of formatting specifiers you can use in numbers.

  • :n Number format: is used to format numbers.
  • Example: Use the :n format specifier to format the number passed to the format() method.

    
    # :n Number format
    var_num = 6372455664.8976778
    var_output = "The number is formatted :n: {:n}".format(var_num)
    print(var_output)
    var_output = "The number is formatted :n: {0} is {0:.3n}".format(8566.76)
    print(var_output)
    

    Output:

    
    The number is formatted :n: 6.37246e+09
    The number is formatted :n: 8566.76 is 8.57e+03
    
  • :d Decimal format: is used to convert binary numbers, into decimal number format.
  • Example: Use the :d format specifier to format the number passed to the format() method.

    
    # :d Decimal format: is used to convert binary numbers, into decimal number format
    var_output = "The Binary number is converted to integer number {0} is {0:d}".format(0b1110)
    print(var_output)
    

    Output:

    
    The Binary number is converted to integer number 14 is 14
    
  • :e Scientific format (e must be lowercase): is used to convert the specified numbers into scientific number format.
  • :E Scientific format (E must be upper case): is similar to the :e and is used to convert a number into a scientific number format.
  • Example: Use the :e and :E format specifier to format the number passed to the format() method.

    
    var_num = 6372455664.8976778
    
    # :e Scientific number format: is used to convert the specified numbers into scientific number format
    var_output = "The Scientific number formatted :e: {:e}".format(var_num)
    print(var_output)
    var_output = "The Scientific number formatted :e: {:e}".format(87)
    print(var_output)
    var_output = "The Scientific number formatted :e: {:e}".format(7654322)
    print(var_output)
    
    # :E Scientific format (must be upper case E) : is used to convert a number into scientific number format (with an upper-case E):
    var_output = "The Scientific number formatted :E: {:E}".format(var_num)
    print(var_output)
    var_output = "The Scientific number formatted :E: {:E}".format(87)
    print(var_output)
    var_output = "The Scientific number formatted :E: {:E}".format(7654322)
    print(var_output)
    

    Output:

    
    The Scientific number formatted :e: 6.372456e+09
    The Scientific number formatted :e: 8.700000e+01
    The Scientific number formatted :e: 7.654322e+06
    
    The Scientific number formatted :E: 6.372456E+09 The Scientific number formatted :E: 8.700000E+01 The Scientific number formatted :E: 7.654322E+06
  • :G General format (G must be upper case): is used to automatically choose between fixed-point and exponential notation based on the magnitude of the number being formatted. Therefore, if the magnitude of the number is greater than or equal to 0.0001 and less than 10,000, then the number is displayed using fixed-point notation. If the magnitude of the number is less than 0.0001 or greater than or equal to 10,000, then the number is displayed using exponential notation.
  • :g General format (g must be lowercase): this is similar to the :G and adds an uppercase exponent notation for large values.
  • Example: Use the :G and :g format specifier to format the number passed to the format() method.

    
    var_num = 6372455664.8976778
    
    # :G General format is similar the :g and but uses uppercase exponent notation for large values. 
    var_output = "The number is formatted :G: {:G}".format(58888888888)
    print(var_output)
    var_output = "The number is formatted :G: {:G}".format(78)
    print(var_output)
    var_output = "The number is formatted :G: {:G}".format(var_num)
    print(var_output)
    
    # :g general format specifier: is used to automatically choose between fixed-point and exponential notation based on the magnitude of the number being formatted.
    var_output = "The number is formatted :g: {:g}".format(58888888888)
    print(var_output)
    var_output = "The number is formatted :g: {:g}".format(78)
    print(var_output)
    var_output = "The number is formatted :g: {:g}".format(var_num)
    print(var_output)
    

    Output:

    
    The number is formatted :G: 5.88889E+10
    The number is formatted :G: 78
    The number is formatted :G: 6.37246E+09
    
    The number is formatted :g: 5.88889e+10 The number is formatted :g: 78 The number is formatted :g: 6.37246e+09
  • :f Fix point number format (f must be lower case): is used to convert specified numbers into a fixed point number, by default it displays 6 decimal maximum. To change these, we have to use a period (.) followed by the number that specifies the number of decimals to be displayed.
  • :F Fix point number format (F must be upper case): is used to convert the specified numbers into a fixed point number. but display inf and nan as INF and NAN.
  • Example: Use the :f and :F and format specifier to format the number passed to the format() method.

    
    var_num = 6372455664.8976778
    
    # :f Fix point number format
    var_output = "The number is formatted :f: {:f}".format(var_num) # default it display 6 decimal maximum 
    print(var_output)
    var_output = "The number is formatted :f: {:.3f}".format(var_num)
    print(var_output)
    var_output = "The number is formatted :f: {:.8f}".format(var_num)
    print(var_output)
    var_output = "The number is formatted :f: {0} in {0:f}".format(float("INF"))
    print(var_output)
    var_output = "The number is formatted :f: {0} in {0:f}".format(float("NAN"))
    print(var_output)
    # :F Fix point number format
    var_output = "The number is formatted :F: {0} in {0:F}".format(77)
    print(var_output)
    var_output = "The number is formatted :F: {0} in {0:F}".format(float("inf"))
    print(var_output)
    var_output = "The number is formatted :F: {0} in {0:F}".format(float("nan"))
    print(var_output)
    

    Output:

    
    The number is formatted :f: 6372455664.897677
    The number is formatted :f: 6372455664.898
    The number is formatted :f: 6372455664.89767742
    The number is formatted :f: inf in inf
    The number is formatted :f: nan in nan
    
    The number is formatted :F: 77 in 77.000000 The number is formatted :F: inf in INF The number is formatted :F: nan in NAN
  • :% Percentage format: is used to convert the specified numbers into a percentage format.
  • Example: Use the :% format specifier to format the number passed to the format() method.

    
    var_num = 6372455664.8976778
    
    # :% Percentage format is used to convert the specified numbers into a percentage format
    var_output = "The number is formatted :%: {:%}".format(var_num)
    print(var_output)
    var_output = "The number is formatted :%: {:%}".format(67)
    print(var_output)
    var_output = "The number is formatted :%: {:%}".format(0.2)
    print(var_output)
    var_output = "The number is formatted :%: {:.0%}".format(0.34)
    print(var_output)
    var_output = "The number is formatted :%: {:.1%}".format(0.66)
    print(var_output)
    

    Output:

    
    The number is formatted :%: 637245566489.767700%
    The number is formatted :%: 6700.000000%
    The number is formatted :%: 20.000000%
    The number is formatted :%: 34%
    The number is formatted :%: 66.0%
    
  • :o Octal format: is used to convert the specified numbers into an octal format.
  • Example: Use the :o format specifier to format the number passed to the format() method.

    
    # :o Octal format is used to convert the specified numbers into octal format
    var_output = "The number is formatted :o: {:o}".format(90)
    print(var_output)
    var_output = "The number is formatted :o: {0} {0:o}".format(677)
    print(var_output)
    

    Output:

    
    The number is formatted :o: 132
    The number is formatted :o: 677 1245
    
  • :b Binary format (b must be lower case): is used to convert the specified numbers (must be an integer) into binary format
  • Example: Use the :b format specifier to format the number passed to the format() method.

    
    # :b Binary format is used to convert the specified numbers (must be integer) into binary format
    var_output = "The number is formatted :b: {:b}".format(44)
    print(var_output)
    var_output = "The number is formatted :b: {0} in binary is {0:b}".format(899876)
    print(var_output)
    

    Output:

    
    The number is formatted :b: 101100
    The number is formatted :b: 899876 in binary is 11011011101100100100
    
  • :x Hex format (x must be lower case): is used to convert the specified number (must be an integer) into Hex format.
  • :X Hex format (X must be upper case): is used to convert the specified number into Hex format
  • Example: Use the :x and :X format specifier to format the number passed to the format() method.

    
    # :x Hex format (must be lower case) is used to convert the specified number (must be integer) into Hex format
    var_output = "The number is formatted :x: {:x}".format(89)
    print(var_output)
    var_output = "The number is formatted :x: {0} in hex is {1:x}".format(255,255)
    print(var_output)
    
    # :X Hex format (X must be upper case) to convert the specified number into upper-case Hex format:
    var_output = "The number is formatted :X: {:X}".format(89)
    print(var_output)
    var_output = "The number is formatted :X: {0} in hex is {1:X}".format(255,255)
    print(var_output)
    

    Output:

    
    The number is formatted :x: 59
    The number is formatted :x: 255 in hex is ff
    
    The number is formatted :X: 59 The number is formatted :X: 255 in hex is FF

Alignment and Sign

Similar to the number formatting category, this category also contains several format specifier that determines how the specified values (strings and numbers) should be formatted when displaying when using the string format() method.

In this section, we will show several format specifiers that align or add new signs to the value or arguments passed to the string format() method. These include:

  • :< The values (arguments) will be left aligned based on the number of spaces specified.
  • Example: Use the :< format specifier to the left to align the value passed to the format() method.

    
    # Alignment and Sign
    # :< Left aligns the result (within the available space)
    txt = "I like {:<9} coding."
    print('I like Python coding.')
    print(txt.format('Python'))
    print(txt.format('Pytho'))
    print(txt.format('Pyth'))
    print(txt.format('Pyt'))
    print("The number of spaces added to align left is : ",9 - len('Python'))
    print("The number of spaces added to align left is : ",9 - len('Pytho'))
    print("The number of spaces added to align left is : ",9 - len('Pyth'))
    print("The number of spaces added to align left is : ",9 - len('Pyt'))
    

    Output:

    
    I like Python coding.
    I like Python    coding.
    I like Pytho     coding.
    I like Pyth      coding.
    I like Pyt       coding.
    
    The number of spaces added to align left is : 3 The number of spaces added to align left is : 4 The number of spaces added to align left is : 5 The number of spaces added to align left is : 6
  • :^ The values (arguments) will be aligned center based on the number of spaces specified.
  • Example: Use the :^ format specifier to center aligns the value passed to the format() method.

    
    # :^ The values (arguments) will be aligned center
    txt = "I like {:^10} coding."
    print('I like Python coding.')
    print(txt.format('Python'))
    print(txt.format('Pytho'))
    print(txt.format('Pyth'))
    print(txt.format('Pyt'))
    
    print("The value is centered and total spaces will be added at both side:",10 - len('Python'))
    print("The value is centered and total spaces will be added at both side:",10 - len('Pytho'))
    print("The value is centered and total spaces will be added at both side:",10 - len('Pyth'))
    print("The value is centered and total spaces will be added at both side:",10 - len('Pyt'))
    

    Output:

    
    I like Python coding.
    I like   Python   coding.
    I like   Pytho    coding.
    I like    Pyth    coding.
    I like    Pyt     coding.
    
    The value is centered and total spaces will be added at both side: 4 The value is centered and total spaces will be added at both side: 5 The value is centered and total spaces will be added at both side: 6 The value is centered and total spaces will be added at both side: 7
  • :> The values (arguments) will be right-aligned based on the number of spaces specified.
  • Example: Use the :> format specifier to right-align the value passed to the format() method.

    
    # :> The values (arguments) will be right aligned based on the number of spaces specified.
    txt = "I like {:>9} coding."
    print('I like Python coding.')
    print(txt.format('Python'))
    print(txt.format('Pytho'))
    print(txt.format('Pyth'))
    print(txt.format('Pyt'))
    
    print("The number of spaces added to align right is : ",9 - len('Python'))
    print("The number of spaces added to align right is : ",9 - len('Pytho'))
    print("The number of spaces added to align right is : ",9 - len('Pyth'))
    print("The number of spaces added to align right is : ",9 - len('Pyt'))
    

    Output:

    
    I like Python coding.
    I like    Python coding.
    I like     Pytho coding.
    I like      Pyth coding.
    I like       Pyt coding.
    
    The number of spaces added to align right is : 3 The number of spaces added to align right is : 4 The number of spaces added to align right is : 5 The number of spaces added to align right is : 6
  • : We use this format specifier (space) to insert an extra space before the numbers (both positive and negative numbers).
  • Example: Use the : format specifier to add spaces to the values passed to the format() method.

    
    # : We use this format specifier (space) to insert an extra space before the numbers (both the positive and negative numbers)
    txt = "Is this a negative or possitive number {:} and {:}."
    print(txt.format(67,-34))
    print(txt.format(-23,55))
    
    txt = "Is this a negative or positive number {:5} and {:7}."
    print(txt.format(67,-34))
    print(txt.format(-23,55))
    

    Output:

    
    Is this a negative or positive number 67 and -34.
    Is this a negative or positive number -23 and 55.
    
    Is this a negative or positive number 67 and -34. Is this a negative or positive number -23 and 55.
  • :- Use a minus sign for negative values only. Note: String is not allowed as an argument instead numbers.
  • Example: Use the :- format specifier to add a minus sign to the value passed to the format() method.

    
    # :- Use a minus sign for negative values only
    txt = "Is this is a negative number {:-}."
    print(txt.format(98))
    print(txt.format(-45))
    

    Output:

    
    Is this is a negative number 98.
    Is this is a negative number -45.
    
  • :+ We use a plus sign format specifier to show if the value is positive or negative.
  • Example: Use the :+ format specifier to show if the passed value to the format() method is negative or positive.

    
    # :+ We use a plus sign to show if the value is positive or negative
    txt = "Is this a negative or positive number {:+}."
    print(txt.format(67))
    print(txt.format(-89))
    

    Output:

    
    Is this a negative or positive number +67.
    Is this a negative or positive number -89.
    
  • := Is used to place the sign (minus or plus) in the left most position.
  • Example: Use the := format specifier to place the sign value passed to the format() method in the left most position.

    
    # := Is used to places the sign (minus or plus) to the left most position.
    txt = "The signs are left aligned {:=3} and {:=5}."
    print(txt.format(+67,-34))
    print(txt.format(-23,+55))
    
    txt = "The signs are left aligned {:=5} and {:=7}."
    print(txt.format(67,-34))
    print(txt.format(-23,55))
    

    Output:

    
    The signs are left aligned  67 and -  34.
    The signs are left aligned -23 and    55.
    
    The signs are left aligned 67 and - 34. The signs are left aligned - 23 and 55.

Thousand Separators

The thousand separators are used to insert either comma ',' or underscore '_' in the numerical values. In this category, there are two types of thousand separators placed inside the placeholders and they are:

  1. ':,' - the comma is used as a thousand separator
  2. ':_' - the underscore is used as a thousand separator

Example: Use these thousand separators':,'and ':_'in the Placeholders when using the string format() method.


# Thousand Separators
# Use the :, to add a comma as a thousand separator
var_num = 637245566
var_output = "The number is formatted {:,}".format(var_num)
print(var_output)

# Use the :_ to add a underscore character as a thousand separator
var_output = "The number is formatted {:_}".format(var_num)
print(var_output)

Output:


The number is formatted 637,245,566
The number is formatted 637_245_566

Miscellaneous

:c This format specifier converts the value into the corresponding Unicode character.

Example: Use ':c' to convert the value passed in the format() method into its corresponding Unicode character.


# :c This converts the assigned value into the corresponding Unicode character
txt = "The signs are left aligned {:c} and {:c}."
print(txt.format(67,34))
print(txt.format(88,90))

Output:


The signs are left aligned C and ".
The signs are left aligned X and Z.

Conclusion

In this article we have extremely discussed the Python String format() Method and we have demonstrated how we can use different strategies for specifying placeholders we also discussed different format specifiers. This article provides a wide range of practical examples that will help you easily understand all the topics covered in this article.

Categorized in: