DEV Community

Cover image for String formatting in Python
libertycodervice
libertycodervice

Posted on

4 1

String formatting in Python

You can do two ways of string formatting in Python. The most easy way is to use f-strings or formatted strings. The other way is similar to the printf function in the C programming language.

The printf way:

>>> print('this is %d %s pet' % (1,'hungry'))
this is 1 hungry pet
>>> 

The f-strings way (has an f in front of the string):

>>> n = 1
>>> s = 'hungry'
>>> print(f'this is {n} {s} pet')
this is 1 hungry pet
>>> 

Obviously the f-strings way is better, but you may find code with the old C style way. So in the C printf way, what is this %?

It lets you output a type of variable. For a string %s, for a number %d.

>>> 
>>> name = 'goofy'
>>> 'my name is %s ' % name
'my name is goofy '
>>> 'that will be %d dollars please' % 5
'that will be 5 dollars please'
>>> 

So you know %d and %s` string formatting codes, but there are others.

Code meaning
%s string (or any object)
%r s, but with repr, rather than the str
%c character
%d a decimal integer
%i integer
%u Unsigned integer
%o octal integer
%x hexadecimal integer
%X x, but the print uppercase
%e floating-point index
%E e, but prints uppercase
%f floating decimal
%F floating decimal
%g e or f floating point
%G floating point e or f
>>> a = 678
>>> print('integer %i is a number' % a)
integer 678 is a number
>>> 

If you want a float, change it:

>>> a = 1.23456
>>> print('float has value of %f ' %a)
float has value of 1.234560 
>>> 

You can use multiple variables in a string:

>>> name = 'goofy'
>>> age = 50
>>> print('I am %s and I am %d years old' % (name,age))
I am goofy and I am 50 years old
>>> 

Read more:

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (1)

Collapse
 
iceorfiresite profile image
Ice or Fire

F-strings make printing SO much easier

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay