InterviewSolution
| 1. |
What are various string formatting features available in Python? |
|
Answer» FORMAT specification symbols (%d, %F, %s etc) are popularly used in C/C++ for formatting strings. These symbols can be used in Python also. Just as in C, a string is constructed by substituting these symbols with Python objects. In the example below, we use the symbols %s and %d in the string and substitute them by values of objects in tuple OUTSIDE the string, prefixed by % symbol >>> name='Ravi' >>> AGE=21 >>> string="Hello. My name is %s. I am %d years old" %(name,age) >>> string 'Hello. My name is Ravi. I am 21 years old'In numeric formatting symbols, the width of number can be specified before and/or after a decimal point. >>> price=50 >>> weight=21.55 >>> string="price=%3d weight=%3.3f" %(price,weight) >>> string 'price= 50 weight=21.550'Since Python 3.x a new format() method has been added in built-in string class which is more efficient and elegant, and is prescribed to be the recommended way of formatting with variable substitution. Instead of % formatting operator, {} symbols are used as place HOLDERS. >>> name='Ravi' >>> age=21 >>> string="Hello. My name is {}. I am {} years old".format(name,age) >>> string 'Hello. My name is Ravi. I am 21 years old'Format specification symbols are used with : instead of %. So to insert a string in place holder use {:s} and for integer use {:d}. Width of numeric and string variables is specified as before. >>> price=50 >>> weight=21.55 >>> string="price={:3d} quantity={:3.3f}".format(price,weight) >>> string 'price= 50 quantity=21.550' |
|