Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




format( ) FUNCTION


format( ) Function is used to as a placeholder for the values to be inserted.


Example :


x = 3
y = 4
z = x + y
result = "The added value of {} and {} is {}"
print(result.format(x, y, z))    


Output :



  The added value of 3 and 4 is 7

So, what we have done is, taken the numbers '3' and '4' in two variables, 'x' and 'y'.


x = 3
y = 4

And stored the added value in a variable named 'z'.


Now, comes the main part, where we have declared a variable named 'result'. And assigned the String 'The added value of { } and { } is { }' to it.


result = "The added value of { } and { } is { }"

The braces '{ }' in the above text are placeholders, that will be displaying some values as mentioned in the 'format( )' method.


And in the next line we see the 'format( )' method with the print statement.


print(result.format(x, y, z))

So, the String variable 'result' calls the 'format( )' method. And what the 'format( )' method does is, based on the order it fills the braces '{ }' with values.


result.format(x, y, z)

java_Collections

Also you can specify the order, based on what the values will be placed.


Example :


x = 3
y = 4
z = x + y
result = "The added value of {1} and {0} is {2}"
print(result.format(x, y, z))


Output :



  The added value of 4 and 3 is 7

Now, if you see the above output, we have changed the order in the format method and we got the new output.


result.format(x, y, z)

java_Collections

Also, we can change the order using keyword.


Example :


x = 3
y = 4
z = x + y
result = "The added value of {p} and {q} is {r}"
print(result.format(p=x, q=y, r=z))


Output :



  The added value of 3 and 4 is 7

Now, what we have done is, given temporary names for variables 'x' - p, 'y' - q and 'z' - r in the 'format( )' method.


print(result.format(p=x, q=y, r=z))

And they got formatted accordingly.


result = "The added value of {p} and {q} is {r}"