Python | format function ()

Counters | File handling | Python Methods and Functions

str.format () is one of the string formatting methods in Python3 that allows multiple replacements and formatting of values. This method allows us to concatenate elements in a string through positional formatting.

Using a single formatter:

Formatters work by placing one or more placeholders and placeholders defined by a pair of curly braces { }, to a string and calling str.format (). The value we want to put in placeholders and concatenate with the string passed as parameters to the formatting function.

Syntax: {} .format (value)

Parameters:
(value): Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype: Returns a formatted string with the value passed as parameter in the placeholder position.

Code # 1 : Simple format demo ().

# Python3 demo program
# str.format () method

 
# using the format parameter in a simple string

print ( "{}, A computer science portal for geeks. "

  . format ( " Python.Engineering " ))

 
# using the format option for
# the value is stored in a variable

str = " This article is written in {} "

print ( str . format ( "Python" ))

 
# string formatting using a numeric constant

print ( " Hello, I am {} years old! " . format ( 18 )) 

Output:

 GeeksforGeeks, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old! 

Using multiple formatters:

Multiple pairs of curly braces can be used when formatting a string. For example, if your sentence requires a different substitution of variables, you can do this by adding a second pair of curly braces and passing the second value to the method. Python will replace placeholders with values ​​in order.

Syntax: {} {} .format (value1, value2)

Parameters:
(value1, value2): Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values ​​passed as parameters in format () method must be equal to the number of placeholders created in the string.

Errors and Exceptions:
IndexError: Occurs when string has an extra placeholder and we didn't pass any value for it in the format () method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3 .... to acces the values ​​passed as parameters. So when it encounters a placeholder whose index doesn't have any value passed inside as parameter, it throws IndexError.

Code # 2:

# Python program showing index error

  
# There are four placeholders, but
# only three values ​​passed

 
# parameters in the formatting function.

my_string = "{}, is a {} {} science portal for {}"

 

print (my_string. format ( " Python.Engineering " , " computer " , "geeks" ))

Output:

 Traceback (most recent call last): File "/ home / 949ca7b5b7e26575871639f03193d1b3.py ", line 2, in print (my_string.format (" Python.Engineering "," computer "," geeks ")) IndexError: tuple index out of range 

Code # 3: Formatters with multiple placeholders.

# Python program that uses multiple places
# holders to demonstrate the str.format () method

 
# Multiple placeholders in a function format ()

my_string = "{}, is a {} science portal for {}"

print (my_string. format ( "GeeksforGeeks" , "computer" , " geeks " ))

  
# different data types can be used for formatting

print ( "Hi! My name is {} and I am {} years old "

  . format ( "User" , 19 ))

  
# Values ​​passed as parameters
# are replaced in the order they are entered

print ( "This is {} {} {} {}"

. format ( "one" , "two" , "three" , " four " ))

Output:

 GeeksforGeeks, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four 

Formatters with positioning and keyword arguments:

When placeholders are {} are empty, Python will replace the values ​​passed through str.format () in order.

The values ​​that exist in the str.format () method are essentially tuple data types , and each distinct value contained in a tuple can be called by its index number, which starts at index number 0. These index numbers can be passed in curly braces that serve as placeholders in the original string.

Syntax: {0} {1} .format (positional_argument, keyword_argument)

Parameters: (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric constants, strings, characters and even variables.
Keyword_argument is essentially a variable storing some value, which is passed as parameter.

Code # 4:

# To demonstrate the use of formatters
# with positional keyword arguments.

 
# Positional arguments
# in order

print ( "{0} love {1} !!" . format ( " Python.Engineering " ,

"Geeks" ))

 
# Swap the number and index with
# placeholder options

print ( "{1} love {0} !!" . format ( "GeeksforGeeks" ,

"Geeks" ))

 

 

print ( "Every {} should know the use of {} {} programming and {}"

. format ( "programmer" , "Open" , "Source" , "Operating Systems" ))

 

 
# Use index numbers
# values ​​to reorder
# they appear on the line

print ( "Every {3} should know the use of {2} {1} programming and {0}"

. format ( "programmer" , "Open" , " Source " , " Operating Systems " ))

 

 
# Keyword arguments are named
# by keyword name

print ( "{gfg} is a {0} science portal for {1}"

. format ( " computer " , " geeks " , gfg = "GeeksforGeeks" ))

Output:

 Python.Engineering love Geeks !! Geeks love Python.Engineering !! Every programmer should know the use of Open Source programming and Operating Systems Every Operating Systems should know the use of Source Open programming and programmer Python.Engineering is a computer science portal for geeks 

Type Specification:

Additional parameters can be included in curly braces in our syntax. Use the format code syntax {field_name: transform} , where field_name specifies the ordinal number of the argument to the str.format () method, and the transform refers to the data type conversion code.

s - strings
d - decimal integers (base-10)
f - floating point display
c - character
b - binary
o - octal
x - hexadecimal with lowercase letters after 9
X - hexadecimal with uppercase letters after 9
e - exponent notation

Syntax:
String {field_name: conversion} Example.format (value)

Errors and Exceptions:
ValueError: Error occurs during type conversion in this method.

Code # 5:

# Show ValueError while
# make forced pr Type conversions

 
# When explicitly converting a floating point number
Number of values ​​in base-10 decimal with "d"
# type conversion we encounter Value-Error.

print ( "The temperature today is {0: d} degrees outside! "

  . format ( 35.567 ))

 
# Write this instead to avoid erroneous values ​​
& # 39; & # 39; & # 39; print (& quot; The temperature today is {0: .0f} degrees outside! & Quot;

. format (35,567)) & # 39; & # 39; "

Output:

 Traceback (most recent call last): File "/home/9daca03d1c7a94e7fb5fb326dcb6d242.py", line 5, in print ("The temperature today is {0: d} degrees outside! ". format (35.567)) ValueError: Unknown format code' d' for object of type 'float' 

Code # 6:

# Convert base-10 decimal integers
# to floating point numeric constants

print ( "This site is { 0: f}% securely {1} !! " .

  format ( 100 , "encrypted" ))

 
# To limit accuracy

print ( "My average of this {0} was {1: .2f}%"

. format ( " semester " , 78.234876 ))

 
# No decimal places

print ( "My average of this {0} was {1: .0f}%"

. format ( "semester" , 78.234876 ))

 
# Convert an integer to its binary or
# with various other converted bases.

print ( " The {0} of 100 is {1: b} "

  . format ( "binary" , 100 ))

  

print ( "The {0} of 100 is {1: o} "

. format ( "octal" , 100 ))

Exit:

 This site is 100.000000% securely encrypted !! My average of this semester was 78.23% My average of this semester was 78% The binary of 100 is 1100100 The octal of 100 is 144 

Substitutions or generating spaces :

Code # 7:

By default, lines are aligned to the left of the field, and numbers — on the right. We can change this by placing the alignment code right after the colon.

  & lt; : left-align text in the field  ^ : center text in the field  & gt; : right-align text in the field 

# To demonstrate distance when
# strings are passed as parameters

print ( "{0: 4}, is the computer science portal for {1: 8}!"

  . format ( "Python.Engineering " , " geeks " ))

 
# To sell monstrate the interval when numeric
# constants are passed as parameters.

print ( " It is {0: 5} degrees outside! "

  . format ( 40 ) )

 
# To demonstrate both string and numeric
# constants passed as parameters

print ( "{0: 4} was founded in {1:16}!"

. format ( "GeeksforGeeks" , 2009 ))

 

 
# To propose tune space alignment

print ( "{ 0: ^ 16} was founded in {1: & lt; 4}! "

  . format ( "GeeksforGeeks" , 2009 ))

  

print ( "{: * ^ 20s} " . format ( "Geeks" ))

Output:

 GeeksforGeeks, is the computer science portal for geeks! It is 40 degrees outside! Python.Engineering was founded in 2009! Python.Engineering was founded in 2009! ******* Geeks ******** 

Applications:

Formatters are commonly used to organize data. Formatters can be seen in their best light when they are used to visually organize large amounts of data. If we're showing databases to users, using formatters to increase the field size and change the alignment can make the output more readable.

Code # 8: To Demonstrate Big Data Organization

# which prints i, i ^ 2, i ^ 3,
# i ^ 4 in the given range

 
# The function outputs values ​​
# unorganized

def unorganized (a, b):

for i in range (a, b):

print (i, i * * 2 , i * * 3 , i * * 4 )

  
# The function prints an organized set of values ​​

def organized (a, b):

for i in range (a, b ):

 

# Using formatters to give 6

# spaces for each set of values ​​

print ( "{: 6d} {: 6d} {: 6d} {: 6d} "

  . format (i, i * * 2 , i * * 3 , i * * 4 ))

 
Driver code

n1 = int ( input ( " Enter lower range: - " ))

n2 = int ( input ( "Enter upper range: -" ))

  

print ( "--- --- Before Using Formatters ------- " )

  
# Calling a function without formatters
unorganized (n1, n2)

 

print ()

print ( "------- After Using Formatters ---------" )

print ()

 
# Call a function containing
# formatters for organizing data
organized (n1, n2)

Output:

 Enter lower range: - 3 Enter upper range: - 10 ------ Before Using Formatters ------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 ------- After Using Formatters --------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561