Python format() with list
Given a list of float values, the task is to truncate all float values to 2 decimal digits. Let’s see the different methods to do the task.
Python3
# Python code to truncate float # values to 2 decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Using format Output = [ '{:.2f}' . format (elem) for elem in Input ] # Print output print (Output) |
Output
['100.77', '17.23', '60.99', '300.84']
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.