String formatting is the process of infusing things in the string dynamically and presenting the string.
There are 3 different methods to format a string in string
- Old style formatting
- String Format method
-
F-string / String interpolation
Old style formatting technique
In this technique we need percent symbol
%
followed by some characters inside the string as placeholder for the values that will be embedded in string.
There are four placeholder or special symbols: %s
→ string%d
→ integer%f
→ float%.(n)f
→ for floating value with n digit precision (n is a positive integer)
These symbols are similar that use in c programming language.
Example 1:
a=5
b=3
print(‘%d + %d = %d’%(a,b,a+b))
# 5+ 3 = 8
Example 2:
name= ‘Anuj’
like=’Bikes’
print(‘My name is %s. I like %s’%(name,like))
# My name is Anuj. I like Bikes.
String format Method
In this technique we use string format method. To use format method we need to use pair of empty curly bracket {}
for each variable we need to embed in the string at place of brackets
Example 1:
a=5
b=3
print(‘{} + {} = {}’.format(a,b,a+b))
# 5+ 3 = 8
Example 2:
name= ‘Anuj’
like=’Bikes’
print(‘My name is {}. I like {}.’.format(name,like))
# My name is Anuj. I like Bikes.
F-string / Literal string interpolation
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format().
Example 1:
a=5
b=3
print(f.‘{a} + {b} = {a+b}’)
# 5+ 3 = 8
Example 2:
name= ‘Anuj’
like=’Bikes’
print(f.‘My name is {name}. I like {like}’)
# My name is Anuj. I like Bikes.
If you like my post consider following me I am sharing content on programming and development. Please comment any improvement on this post.
You can contact me on-
Linkedin: https://www.linkedin.com/in/rhlgt/
Twitter: https://twitter.com/rahulgtst
Top comments (0)