String formatting differences

Hi, I am struggling to understand the difference in string formatting with python

Pay particular attention to the last lines of code

Take a look at this code:

import random 
player_name ='Gandalf'
player_type ='Wizard'
def roll():    
     number = random.randint(1,20)    
     return number 
print('A troll attacks!')
troll_roll = roll()
player_roll = roll()
**print('Player: %s Troll: %s'%(str(player_roll),str(troll_roll)))```**

What are the advantages to printing using the above type of string formatting, as opposed to something like

print('Player: ', player roll, ' Troll: ', troll_roll)

Especially if I convert the variables to strings ahead of time? I feel like the second example reads better. Which should I use ?

That style of print formatting was mostly used in Python 2 days, before the str.format() function was introduced. It is known as modulo formatting.

The modulo symbol has two roles. Inside the string template it signifies a placeholder and data type, and outside of the string it indicates the parameter list.

"%s"                =>  placeholder for str type

"..." % (..., ...)  =>  parameter list

If the values we are passing in are numbers (int or float) then we don’t need to convert, just set the placeholder to that type.

%d or %i  =>  digit, i.e., int

%f        =>  float
2 Likes

so would this be a more modern solution ?

troll_roll = str(roll())
player_roll = str(roll())

print('Player: ', player_roll, 'Troll: ', troll roll)
1 Like

That is not string formatting, but raw output. The comma separated values can be mixed type in that statement. Again, no conversion needed.

>>> print ("...", 1089, "...", 42)
... 1089 ... 42
>>> 

Consider your statement from the OP…

print('Player: %s Troll: %s'%(str(player_roll), str(troll_roll)))

We would write this as,

print ('Player: %d Troll: %d' % (player_roll, troll_roll))

https://pyformat.info/


Bottom line, we let the placeholder do the conversion work, given the type to expect.

1 Like

If

print("Player: %d Troll: %d" % (player_roll, troll_roll))

Is string formating, then what’s the name of this:

print(f"Player: {player_roll} Troll: {troll_roll}")

I have seen it before but I’m not sure what it’s called.

1 Like

That is also string formatting only with the more recent, f-string template. It is more closely related to the older, str.format() in terms of how the placeholders are written.

1 Like