I don't understand what those two things do and how they work

i tried researching off google, but i couldnt get a direct answer

Edited by ffs82defxp: n/a

7 Years
Discussion Span
Last Post by vegaseat

%s Serves as a placeholder for a string value that will be supplied with values placed after the last % character in the print statement. Likewise, %d serves as a placeholder for a signed integer decimal value. For example:

qtylist = [5, 7, 3, 11, 2]
unitlist = ['bottles', 'flocks', 'loaves', 'bags', 'cups']
itemlist = ['beer', 'geese', 'bread', 'flax', 'tea']

for i in range(5):
    print "Give me %d %s of %s" % (qtylist[i], unitlist[i], itemlist[i])

You can read more about it at http://docs.python.org/library/stdtypes.html#string-formatting-operations


Here is another example of formatting a string with %s and %d placeholders. The syntax pretty much follows the C printf() function formatting.

def visits(name, n):
    """ adds an s to 'time' if n > 1 """
    return "%s visited you %d time%s" % (name, n, ['','s'][n>1])

print( visits("Harry", 1))
print( visits("Lorie", 3))

"""my display -->
Harry visited you 1 time
Lorie visited you 3 times

Another example would be currency formatting. It uses the %f placeholder for floating point numbers.

def format_dollar(amount):
    """format amount to dollars and cents"""
    return "$%0.2f" % amount

price = 123.95
tax_rate = 0.07
dollar_price = format_dollar(price)
dollar_tax = format_dollar(price * tax_rate)
print( "The item costs %s tax is %s" % (dollar_price, dollar_tax) )

"""my display -->
The item costs $123.95 tax is $8.68

Edited by Lardmeister: n/a

Votes + Comments
Neat examples.

Just a note that Python3 has introduced a new format() function, but you can still use the % formatting.

Here is an example ...

# works with Python2 and Python3
sf = "I will pick up %s in %d hours" % ('Mary', 3)

# works with Python3.1 (string is default)
sf2 = "I will pick up {} in {:d} hours".format('Mary', 3)

"""my output -->
I will pick up Mary in 3 hours
I will pick up Mary in 3 hours

Edited by vegaseat: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.