Member-only story

String formatting in Python.

Bilal K.
2 min readFeb 12, 2021

--

Python turns 30 this week :)

Photo by Ck Lacandazo from Pexels

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…

--

--

Bilal K.
Bilal K.

Written by Bilal K.

Software Engineer, I share tips and tools to help fellow developers level up.

No responses yet

Write a response