Bilal K.

Bilal K.

String formatting in Python.

String formatting in Python.

Subscribe to my newsletter and never miss my upcoming articles

Python turns 30 this week :)

Photo by [**Ck Lacandazo](https://cdn.hashnode.com/res/hashnode/image/upload/v1615902229362/Z62avu4Li.html)** from [**Pexels](https://www.pexels.com/photo/woman-holding-brown-snake-3445161/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels)**Photo by **Ck Lacandazo from [Pexels](pexels.com/photo/woman-holding-brown-snake-..

Python turns 30 this week and it’s a fun way to celebrate the birthday by documenting different string formats tricks in a form of a blog.

In this post, we’ll learn good practices for String formatting. There are two available options, one is using format() while in the second one “%” operator is used to formatting a set of variables enclosed in a “tuple”, along with a format string, which contains normal text together with “argument specifiers”. Let’s dive into the code.

1- String Formatting using % operator and format()

The code we see everywhere to print goes like this.

x= 24
y = 97
print ('x=',x, 'and y=', y)

#output
x= 24 and y= 97

But as you may have noticed some weird spaces in the output. Also, this is not suitable as we have to do a lot of work with more variables to print.

print ('x=%d and y=%d' %(x,y))  #using % operator
print ("x={} and y={}".format(x,y))

#output
x=24 and y=97
x=24 and y=97

The %d to tell where to substitute the value of x and y represented as an int in this example. For string and float use, %s and %f respectively.

x=24.51
y=12
print ('x=%.2f and y=%d'%(x,y))

#output
x=24.51 and y=12

Similarly, for rounding, we can use the specific number to which we want to round the number(In my case, I’m rounding it to two decimal points).

2-Padding

Let’s take a string and apply some padding to it.

l = [1,98,21,200]

Let’s print the items of this list using the loop.

for i in l:
print ("%d"%i)

#output
1
98
21
200

Now implement the padding.

for i in l:
print ("%3d"%i)

#output
  1
 98
 21
200

In the print statement, %3d takes an integer argument and assigns a minimum width of 3. So, it is aligned to the right.

The complete guide on String Formatting is available here.

So that’s it! I hope you found it helpful, and also I hope that you have a nice day.

Till next time :) Happy Learning.

If you liked this article make sure to 👏 it below, and follow me on Twitter here

 
Share this