Strings Formatting in Python

rahulgtst

Rahul Gupta

Posted on January 3, 2023

Strings Formatting in Python

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
Enter fullscreen mode Exit fullscreen mode

Example 2:

name= ‘Anuj’
like=’Bikes’
print(‘My name is %s. I like %s’%(name,like))
# My name is Anuj. I like Bikes.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Example 2:

name= ‘Anuj’
like=’Bikes’
print(‘My name is {}. I like {}.’.format(name,like))
# My name is Anuj. I like Bikes.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Example 2:

name= ‘Anuj’
like=’Bikes’
print(f.‘My name is {name}. I like {like}’)
# My name is Anuj. I like Bikes.
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
rahulgtst
Rahul Gupta

Posted on January 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related