Home » Python

Python String | format() Method with Example

Python String | format() Method with Example, this is an in-built method of Python and it format given string, it is useful when we create/format string with the values.
Submitted by IncludeHelp, on July 19, 2018

String.format() Method

format() method is used to format the string (in other words - we can say to achieve the functionality like printf() in C language).

When we need to display the values of the variables inside the string, we can format it by placing {} where we want to place the value. {} is a replacement field, that replaces with the given value in format() method.

The field {} contains the index to replace, the value specified in the format function.

Let suppose, there are three values specified in the format method, {0} for the first value, {1} for the second value and {2} for the third value and so on will be used.

Syntax:

 String.format(parameter1, parameter2,...)

Here, parameter1, parameter2, ... are the values/variables that will print within the string by replacing the field {N}. Where N is the index of the parameter.

Example:

    print "{0}, {1} and {2}".format("ABC", "PQR", "XYZ")
    This statement will print "ABC, PQR, and XYZ"

Example program 1: (printing name, age in different output formats)

# printing name
print "My name is {0}".format("Amit")

# printing name and age 
print "My name is {0}, I am {1} years old".format ("Amit", 21)

# printing name and age through variables
name = "Amit"
age = 21

print "My name is {0}, I am {1} years old".format (name,age)

Output

    My name is Amit
    My name is Amit, I am 21 years old
    My name is Amit, I am 21 years old

Example program 2: (Calculating SUM, AVERAGE, and printing in different output formats)

a = 10
b = 20

sum = a+b

# output 1
print "sum = {0}".format (sum)

# output 2
print "Sum of {0} and {1} is = {2}".format (a, b, sum)

# finding average and printing 
a = 11
b = 20

sub = a+b

print "Average of {0} and {1} is = {2}".format (a, b, float(sum)/2)

Output

    sum = 30
    Sum of 10 and 20 is = 30
    Average of 11 and 20 is = 15.0



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.