Professional Documents
Culture Documents
String Formatting With Python
String Formatting With Python
String formatting, also known as String interpolation, is the process of inserting a custom string
or variable dynamically in predefined text – to provide a consolidated string. These are used to
simplify utilization of variables in printing messages and errors. These allows easy customization
during generating strings.
2. Format string using format() method – This work by putting in one or more
replacement fields and placeholders defined by a pair of curly braces { } into a string and
calling the str.format(). In addition to the benefits of the placeholder method, the
str.format() method allows insert object by using index-based position and assigned
keywords. This is also helpful in reusing an inserted object to avoid duplication
num1 = 5
num2 = 7
print('The larger number of {a} and {b} is {b}, not {0:0.3f}'.format(6, a = num1, b =
num2))
Output: The larger number of 5 and 7 is 7, not 6.000
3. Format String using F-strings – This is the most advanced string formatting mechanism.
It is also known as Literal String Interpolation. Though the formatting technique is very
similar to str.format(), it is concise, convenient and simpler. It allows to insert arbitrary
Python expressions (like arithmetic operations) in it.
a=5
print(f'{a} is {a}. It is not {a * 2}, nor {a:0.2f}')
Output: 5 is 5. It is not 10, nor 5.00