String Formatting in python
To inject items in the string we, use string formatting. To do such things using string concatenation we will have to write a lot of breaking and addition in the string.
businessman = 'Ankush'
money = 100
'Last night, '+businessman+' earned '+str(money)+' rupees.' # concatenation
f'Last night, {businessman} earned {money} rupees.' # string formatting
There are three ways to perform string formatting.
- Formatting the string using
%(modulo) character. - Formatting using
.format()method, which is an inbuilt string method. - Formatting using string literals, called f-strings, only available in puthon 3.6 or newre
We will cover all of them in this very article.
Formatting the string using '%' (modulo), placeholder.
% is known as the string formatting operator or the placeholder, we can inject elements in a string using this placeholder.
print("Let's inject %s, my name." %'Ankush Pandey')
You can inject multiple characters simultaneously
print("Now lets inject my first name %s and my last name %s" %('Ankush','Pandey'))
You can also use variables to inject elements
x, y = 'Ankush','Pandey'
print("Now lets inject my first name %s and my last name %s"%(x,y))
Different format conversion methods.
To convert a python object into a string, there are two main methods the first one is the %s or str() and the secon one is the %r or repr()method. In the first method the objects are converted to string without a string representation, but in the second method the objects are converted to the strings with a string representation.
print("Let's inject %s, my name." %'Ankush Pandey')
print("Let's inject %r, my name." %'Ankush Pandey')
As another example, normally \t inserts a tab into a string. But when used with used with %r or repr() the \t is printed as a normal charecter not an escape sequence.
print("Let's inject %s, my name." %'Ankush \tPandey')
print("Let's inject %r, my name." %'Ankush \tPandey')
Unlike %s operator, the %d operator tries to converts object into integers first, without rounding. After that I converts them to string.
print('Please give me %s dollars.' %20.55)
print('Please give me %d dollars.' %20.55)
Floating point numbers padding and precision
%a.bf is written to format floating point numbers. Here, a represents the minimum number of characters the string should contain. If the entire floating point number does not has that much numers then it will be padded with blank spaces. b represents the number of numbers after the decimal.
print("Let's write a floating point number: %5.2f" %(13.144))
print("Let's write a floating point number: %1.0f" %(13.144))
print("Let's write a floating point number: %1.5f" %(13.144))
print("Let's write a floating point number: %10.2f" %(13.144))
print("Let's write a floating point number: %25.3f" %(13.144))
If you want to learn more about the floating point numbers then please visit: https://docs.python.org/3/library/stdtypes.html#old-string-formatting
Multiple Formatting
Nothing prohibits using more than one conversion tool in the same print statement:
print('First: %s, Second: %5.2f, Third: %r' %('hi!',3.5769,'hello!'))
String formating with .format()
Till now we have seen that how we can format a string using the modulo % operator, now lets see an even better method to use for formatting, that is .format():
'Inserint the {} and the second {}'.format('item1','item2')
Lets see some examples:
print('We are goint to add my name here: {} '.format('Ankush Pandey'))
Let's see that what advantages we get when we use .format() over %s.
1. It supports inseritng of objects using indexes.
print('{2} {1} {0} {3}'.format('item1','item2','item3', 'item4'))
2. IAssigned kewords can be inserted if you dont want to use indexing:
print('{a} {b} {c}'.format(a='item1',b='item2',c='item3'))
print('{a} {b} {c}'.format(a=1,b='Two',c=12.3))
3. Reusability of the inserted object.
print('%s %s' %('item1','item1'))
# vs.
print('{a} {a}'.format(a='item1'))
how you implement alignment padding and precision using .format() method
We can specify field length, precision or alignment using the curly braces, you can refer to the examples given below.
print('{0:10} | {1:15} |'.format('Employee', 'salary in LPA'))
print('{0:10} | {1:15} |'.format('Ankush', 9.0))
print('{0:10} | {1:15} |'.format('Ankush1', 11))
You can use the symbols '<' and '^' and '>' to specify left right and centre alignment respectively, by default python uses left alignment
print('{0:<12} | {1:^12} | {2:>12}'.format('Left align', 'Center align', 'Right align'))
print('{0:<12} | {1:^12} | {2:>12}'.format(23, 577, 99324))
We can create padding with the assignment operator to fill the spaces.
print('{0:=<12} | {1:-^12} | {2:.>12}'.format('Left align', 'Center align', 'Right align'))
print('{0:=<12} | {1:-^12} | {2:.>12}'.format(23, 577, 99324))
We can manage the field width and precision in .format() method, the implementation will be similar to the % placeholder method.
print('I am Iron man and my salary is: %10.2f $LPA' %10.222)
print('I am Iron man and my salary is: {0:10.2f} $LPA'.format(10.444))
If you want to learn more about the .format() method, I will recommend you to visit this documentation link https://docs.python.org/3/library/string.html#formatstrings
String formatted using f-strings or string literals
f-string method is even better that the .format() method. In this method you can inserty a variable from outside just by writting its name rather passing it in the .format() method.
name = 'Iron man'
print(f"My name is {name}.")
Use !r if you want the inserted string to be in representation form repr()
print(f"My name is {name!r}.")
Float formatting is don as follows
"result: {value:{width}.{precision}}"
num = 65.54389
print("My salary in dolars is: {0:10.4f}".format(num))
print(f"My salary in dolars is: {num:{10}.{6}}")
Note:
- The precision in f-literal method represents the total length of the number, unlike the
.format()method where it represents only the length of the charecters after the decimal. - You can always use
.format()method syntax inside an f-string:
num = 45.4589
print("My salary in dolars is: {0:10.4f}".format(num))
print(f"My salary in dolars is: {num:{10}.{5}}")
num = 23.45
print("My 10 character, four decimal number is:{0:10.4f}".format(num))
print(f"My 10 character, four decimal number is:{num:10.4f}")
To learn more bout the f-string literals you can visit this documentation also: https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Thankyou!

So helpful sir
ReplyDelete