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
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
%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
"""
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)
print(sf)
# works with Python3.1 (string is default)
sf2 = "I will pick up {} in {:d} hours".format('Mary', 3)
print(sf2)
"""my output -->
I will pick up Mary in 3 hours
I will pick up Mary in 3 hours
"""
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.