Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I don't understand what %s and %d do and how they work.

2 Answers

0 votes
by (106k points)

In, Python %s and %d are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

name = 'abc' 

number = 2 

print('%s %d' % (name, number))

This code will print abc 2.

0 votes
by (108k points)

Please be informed that the '%d' is for decimal numbers in Python whereas the '%s' is for generic string or object and in the case of an object, it will get converted to a string type data.

Refer to the below code for reference:

name ='giacomo'

number = 4.3

print('%s %s %d %f %g' % (name, number, number, number, number))

The output:

giacomo 4.3 4 4.300000 4.3

As you can notice that the %d will truncate to integer, %s will maintain formatting, %f will print as float, and %g is used for generic number:

print('%d' % (name))

The above code will throw an exception as we cannot able to convert a string format data to number format data.

Related questions

Browse Categories