Python basics - String Formatting

Published On: 2019/09/21

When do use formatter? If in case we want to represent the content of a string in a specific order then it would be good to use a fomatter. Formatting of string is mostly seen in the logger statements.

eg: If we need to log a message Customer with id [customer Id] is registered for the event [event name] then we can use the formatter function to generate the required string.

1
2
3
message = "Customer with id {} is registered for the event {}".format(1234,"Tech Event 2019");
print(message);
//Expected result: Customer with id 1234 is registered for the event Tech Event 2019

If the values are packed into an array we can use the feature called unpacking,(* symbol before the variable), in the format function to replace the placeholders with the values given in the array.

vals = ["1234", "Tech Event 2019"]
message = "Customer with id {} is registered for the event {}".format(*vals)
print(message);

In case we need to create an html structure where the same element structure is repeating, use of repeating indices in the formating string helps us to create the required structure.

tableStruct = "{0}{1}{2}{2}{2}{3}{3}".format("<div class='table'>","<div class='row'>","<div class='col'></div>","</div>");
print(tableStruct);

The arguments of the format function can be access by name in the string which needs to be formatted. In the below example the values of customerId and eventName are assigned to variable name a, b respectively and these variable names are used in the formatting string.

def registrationMessage(customerId,eventName):
    return "Customer with id {a} is registered for the event {b}".format(a=eventName,b=customerId);    

print(registrationMessage(1234,"Tech Event 2019"));

Another important formatting requirement is to format a date value.

import datetime
dateVal = datetime.datetime(2019, 9, 30, 12, 15, 58)
formatedDate= "{:%Y-%m-%d %H:%M:%S}".format(dateVal);
print(formatedDate);
//Expected Result: 2019-09-30 12:15:58 

The below code format datetime with millisecods, 3 decimal places behind seconds

import datetime
dateVal = datetime.datetime(2019, 9, 30, 12, 15, 58)
formatedDate=dateVal.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3];
print(formatedDate);
//Expected Result: 2019-09-30 12:15:58.000 

comments powered by Disqus