Python: Formatting strings using the %

This method allows you to specify placeholders for objects with formatting specified to the left of the % operator in the string. Then, the corresponding objects specified to the right of the % operator are substituted into these placeholders.

Basic output formats for the % operator

Format Description
'%d' Decimal integer
'%o' Octal number
'%x' Hexadecimal number (lowercase letters)
'%X' Hexadecimal number (uppercase letters)
'%f', '%F' Floating-point number
'%e' Floating-point number in lowercase exponential format
'%E' Floating-point number in uppercase exponential format
'%c' Character (or ASCII value)
'%s' String

Example formatting strings using the %


print('1/3=%d' %(1/3))
print('1/3=%f' %(1/3))
print('1/3=%e' %(1/3))
print('1/3=%s' %(1/3))
print('The number 9 in octal numeric system = %o' %(9))
print('The number 10 in hexadecimal numeric system = %X' %(10))
print('%c' %'A')
print('%c' %65) 

Output Terminal:


1/3=0
1/3=0.333333
1/3=3.333333e-01
1/3=0.3333333333333333
The number 9 in octal numeric system = = 11
The number 10 in hexadecimal numeric system = A
A
A

            

In formatted output, after the % symbol in the format specification, additional settings can be specified.

Parameter Description
Flag Specifies how "extra" free positions will be filled in during output. It takes the following values:

'0' - The free space is filled with zeros;

'' - The free space is filled with spaces on the left;

'-' - The free space is filled with spaces on the right.

Minimum number of characters to output A decimal number indicating the number of positions to output. If the output value contains fewer characters, the rest are filled according to a specific rule specified in the "flag" parameter.
Output precision The desired output precision. When specifying precision, a dot is first placed, followed by the number indicating the precision itself (for numbers - the number of digits after the decimal point, for strings - the number of characters to be output).

Code example:


print("'%.2f'" %(1/3))
print("'%10.3f'" %(1/3))
print("'%-10.2f'" %(1/3))
print("'%010d'" %(5))
print("'%10s'" %('Python'))
print("'%.2s'" %('Python'))        
                
                

Output:


'0.33'
' 0.333'
'0.33 '
'0000000005'
' Python'
'Py'         
            
                

Python: Formatting strings using the method format()

The format() method of formatted output allows you to set values ​​in specific positions of a string, specified as its arguments. Placeholder positions are marked by curly braces "{}". Braces can be either empty or with parameters. If the braces are empty, then the arguments are substituted into the braces in the order of occurrence, i.e., the first argument is substituted into the first brace in the string, the second into the second brace, and so on. If you put numbers (indexes) in the braces, then the arguments will be substituted in place of the specified number. Argument indexing starts from 0. Named arguments can also be used.

Basic output formats for the format() method are:

Format Description
{:d} Decimal integer
{:o} Octal integer
{:x} Hexadecimal integer (lowercase)
{:X} Hexadecimal integer (uppercase)
{:f}, {:F} Floating-point number in standard format
{:e} Floating-point number with exponent (lowercase)
{:E} Floating-point number with exponent (uppercase)
{:c} Single character or ASCII value
{:s} String

Code example:


print('Hello, {}!'.format('Python'))
s = 'Hello, {}!'
n = 'Python'
print(s.format(n))
print('{} {} {}'.format('Hello', 'Python', 'Java'))
print('{1} {0} {2}'.format('Hello', 'Python', 'Java'))
print('{a} + {b} = {c}'.format(a=1, b=2, c=3))        
                
                

Output:


Hello, Python!
Hello, Python!
Hello Python Java
Python Hello Java
1 + 2 = 3        
            
            

Code example:


print("'1/3 = {0:10f}'".format(1/3))
print("'1/3 = {0:.2f}'".format(1/3))
print("'{0:.2s}'".format('Python'))
print("'1/3 = {0:10.2f}'".format(1/3))      

Output:


'1/3 = 0.333333'
'1/3 = 0.33'
'Py'
'1/3 = 0.33'      

Additional options of the format() method

The format method also allows controlling text alignment during output, specifying a placeholder for empty positions, and managing the display of the "+" sign for positive numbers. Additional flags for the format() method:

Format Description
'<' Left alignment
'>' Right alignment
'=' Sign placed after padding. Only works for numbers.
'^' Center alignment
'+' Sign is always included, for both positive and negative numbers.
'-' Negative numbers are displayed with a minus sign, positive numbers have no sign.
' ' Negative numbers are displayed with a minus sign, positive numbers have a space.

Code example:


print("'1/3 = {0:<15f}'".format(1/3))
print("'1/3 = {0:>15f}'".format(1/3))
print("'1/3 = {0:^15f}'".format(1/3))
print("'1/3 = {0:*^15f}'".format(1/3))
print("'1/3 = {0:*=15f}'".format(-1/3))
print("'{0:+5}:{1:+5}'".format(3,-3))
print("'{0:5}:{1:5}'".format(3,-3))
print("'{0: }:{1: }'".format(3,-3))    
  
  

Output:


'1/3 = 0.333333 '
'1/3 = 0.333333'
'1/3 = 0.333333 '
'1/3 = ***0.333333****'
'1/3 = -******0.333333'
' +3: -3'
' 3: -3'
' 3:-3'      
  
  

f'' string

Python's f-strings offer several advantages over traditional string formatting methods like % formatting or str.format(). Here are some key advantages:

  • Readability: f-strings are more readable and concise compared to other formatting methods. They allow you to directly embed Python expressions and variables within the string, making the code easier to understand and maintain.

  • Ease of Use: f-strings are easy to use and remember. You simply prefix the string with f or F and then include expressions or variables inside curly braces {}.

  • Performance: f-strings are generally faster than other formatting methods because they are evaluated at runtime rather than at formatting time. This can lead to improved performance, especially in situations where formatting is done repeatedly or in performance-critical code.

  • Full Python Expressions: With f-strings, you can include full Python expressions inside the curly braces, not just simple variable names. This allows for more flexibility and power when formatting strings.

  • Integration with IDEs: Many modern IDEs provide enhanced support for f-strings, including syntax highlighting, code completion, and error checking. This makes it easier to work with f-strings in your code editor.

  • Fast:f-strings are almost 3.5x faster than str.format()

Code example:


num = 42
print(f"Decimal integer: {num:d}")
print(f"Octal integer: {num:o}")
print(f"Hexadecimal integer (lowercase): {num:x}")
print(f"Hexadecimal integer (uppercase): {num:X}")
float_num = 3.14159
print(f"Floating-point number in standard format: {float_num:.2f}")
print(f"Floating-point number in standard format (uppercase): {float_num:F}")
print(f"Floating-point number with exponent (lowercase): {float_num:e}")
print(f"Floating-point number with exponent (uppercase): {float_num:E}")
char = 'A'
print(f"Single character: {char:c}")
string = "Hello, World!"
print(f"String: {string:s}")  
  
  

Output:


Decimal integer: 42
Octal integer: 52
Hexadecimal integer (lowercase): 2a
Hexadecimal integer (uppercase): 2A
Floating-point number in standard format: 3.14
Floating-point number in standard format (uppercase): 3.141590
Floating-point number with exponent (lowercase): 3.141590e+00
Floating-point number with exponent (uppercase): 3.141590E+00
Single character: A
String: Hello, World!     
  
  

Code example:


import datetime
today = datetime.datetime.now().date()
print(f'Today is {today}')
# or
print(f'Today is {datetime.datetime.now().date()}')   

Output:


Today is 2024-04-28
Today is 2024-04-28

Code example:


user = dict(name='John', age=25, favorite_language='Python')
print(f"The user {user.get('name')} is {user.get('age')} years old and likes to code in {user.get('favorite_language')}")
# or
print(f"The user {user['name']} is {user['age']} years old and likes to code in {user['favorite_language']}")

Output:

The user John is 25 years old and likes to code in Python
The user John is 25 years old and likes to code in Python

Links: Python documentation


[1] Python string Formatting Operator


[2] Python format string syntax