Python: String Formatting using f-string

Python’ formatted string literals or f-string makes the string formatting very easier. The f-string was introduced in Python 3.6 under PEP-498.  It has easy syntax compared to the previous string formatting methods.

The f-string is beginning with the letter f or F and next, the string is enclosed in single or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

In [1]:
fname = "Mark"
lname = "Ronson"

y = f'Hello, {fname} {lname}!'   # f-string using single quotation mark
print(y)
Out[1]: Hello, Mark Ronson!
In [2]:
fname = "Mark"
lname = "Ronson"

print(f'''Hello, {fname} {lname}!''')  # f-string using triple quotation mark
Out[2]: Hello, Mark Ronson!

Syntax:

{value : [<flags>][<width>][.<precision>][<type>]}

Floating-point formatting – Passing a precision after the ':' will cause the output to be a specified decimal place.

In [3]: print(f'The share price of apple increased by {52.1234:.2f}%')
Out[3]: The share price of apple increased by 52.12%

f-string width – Passing an integer after the ':' will cause that field to be a minimum number of characters wide.

In [4]: print(f'{"banana":10} ==> {150:10d}')
Out[4]: banana     ==>        150

f-string with the arithmetic operation – Perform the arithmetic calculation within { }

In [5]: print(f'The sum: {2} + {3} = {2+3}')
Out[5]: The sum: 2 + 3 = 5

f-string with Python’ Dictionary – Pass the Python dictionary to print the data.

In [6]: 
fruit = {'Banana':25,'Apple':50,'Orange':30}
for f in fruit:
    print(f'{f} ==> ${fruit[f]}')
Out[6]: 
Banana  ==> $25
Apple  ==> $50
Orange  ==> $30

f-string calling function – You can call the python function within the f-string format.

In [7]: 
def sum_fn(a,b):
    return a+b

print(f'The sum: {sum_fn(2,3)}')
Out[7]: The sum: 5

f-string alignment – You can control over the appearance of the format string.

  • > – Right Justified
  • < – Left Justified
  • ^ – Center Justified
In [8]: print(f'{"Hello":>10}')      # width: 10 & Right Justified
Out[8]:      Hello

In [9]: print(f'{"Hello":<10}')      # width: 10 & left Justified
Out[9]: Hello     

In [10]: print(f'{"Hello":^10}')     # width: 10 & Center Justified
Out[10]:   Hello   

In [11]: print(f'{"Hello":@>10}')    # width: 10 & Right Justified and fill as '@'
Out[11]: @@@@@Hello

In [12]: print(f'{"Hello":*^10}')    # width: 10 & center Justified and fill as '*'
Out[12]: **Hello***

Type Conversion – You can make the type conversion in octal, hexadecimal, binary etc using f-string.

In [13]: print(f'The Octal value of {10} is {10:o}')
Out[13]: The Octal value of 10 is 12

In [14]: print(f'The Hexadecimal value of {10} is "{10:x}"')
Out[14]: The Hexadecimal value of 10 is "a"

In [15]: print(f'The binary representation of {10} is "{10:b}"')
Out[15]: The binary representation of 10 is "1010"

The Flag Option:

Option Meaning
'#' Generally, the floating-point number will not display a decimal point, if there are not any digit exist after the decimal point. The Flag # force to include the decimal point in the formatted output.

For the Hexadecimal and Octal type, the Flag# force to include the base information in the formatted output. The integer type avoids considering Flag-#.

'0' When the specified value of the width field is larger than the output length, the extra space is padded to the output. This 0-Flag padded the string with zero instead of space.
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers (this is the default behavior).
space indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

 

Flag # – '#' option adds the prefix '0b''0o', or '0x' to the output value binary, octal and hexadecimal respectively.

In [16]: print(f'The Octal value of {10} is {10:#o}')
Out[16]: The Octal value of 10 is 0o12

In [17]: print(f'The Hexadecimal value of {10} is "{10:#x}"')
Out[17]: The Hexadecimal value of 10 is "0xa"

In [18]: print(f'The binary representation of {10} is "{10:#b}"')
Out[18]: The binary representation of 10 is "0b1010"

Example of Flag   ‘+’, ‘-‘ & ‘ ‘

In [19]: print(f'{1.23:f} & {-1.23:f}')      # Defalult: No sign
Out[19]: 1.230000; -1.230000

In [20]: print(f'{1.23:+f} & {-1.23:+f}')    # Use '+' sign
Out[20]: +1.230000; -1.230000

In [21]: print(f'{1.23:-f} & {-1.23:-f}')   # USe '-' sign
Out[21]: 1.230000; -1.230000

In [22]: print(f'{1.23: f} & {-1.23: f}')   # Use ' '(space) sign
Out[22]: ' 1.230000; -1.230000'

.     .     .

Curly Braces – You can print the {} braces in the output string using a double set of braces with f-string formatting.

In [23]: print(f'{{"Good Morning"}}')
Out[23]: {"Good Morning"}

.     .     .

Leave a Reply

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

Python Tutorials