Python string format() method

In this blog, we are going to learn Python format() function with their implementation.

So if you have learned C, JAVA, or  C++  before studying Python you know we used %c, %s, and %d for printing the values in printf() function. Python language format() function works similarly to that.

Where:

  • % is used for format specifiers.
  • %c, %s, and %d are used to print a character, string, and integer value respectively.

Implementation Without Using Format() Function

Let’s understand with some examples,

Code:

user = ['Rohit','suryakumar','hardik','pollard']
mobile=['samsung','nokia','oneplus','100rs vala mobile']
for i in range(0,len(user)):
    print("mobile used by ",user[i],"is",mobile[i])

Explanation:

  1.  “user-list” with their attributes.
  2. “mobile list” with their attributes.
  3. the for loop runs till the length of the “listener”.
  4.  printing the values.

Output:

mobile used by Rohit is samsung
mobile used by suryakumar is nokia
mobile used by hardik is oneplus
mobile used by pollard is 100rs vala mobile

Implementation Using Format() Function

The same code which is discussed above section is used to implement using Python format() function.

Code:

user = ['Rohit','suryakumar','hardik','pollard']
mobile=['samsung','nokia','oneplus','100rs vala mobile']
#for i in range(0,len(user)):
#    print("mobile used by ",user[i],"is",mobile[i])
for i in range(0,len(user)):
    template="computer used by {0} is {1}"
    print(template.format(user[i], mobile[i]))

Explanation:

  1. “user-list” with their attributes.
  2. “mobile list” with their attributes.
  3. comment
  4. comment
  5. for loop which is run till the length of the “listener”.
  6. template variable with a format() function syntax (in brackets with parameter {0} and {1} is getting values from user[i] and mobile[i] respectively & if we swap the parameter like {1} and {0} is getting values from mobile[i] and user[i] respectively).
  7. printing the values.

Output:

computer used by Rohit is samsung
computer used by suryakumar is nokia
computer used by hardik is oneplus
computer used by pollard is 100rs vala mobile

However, in the above, it looked similar but when we are processing or manipulating large amounts of data then the format() function becomes quite useful.

You may also learn and implement,

Leave a Reply

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