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
Quick primer (builds on , and ): the % operator is the older "printf-style" formatter that your posts showed. It is still supported, but it has a few practical traps and a couple of modern alternatives worth using instead. (projects.localizethedocs.org)
Common gotchas and rules to remember: %s uses str() (good for general text) while %r uses repr() (handy for debugging), and %d is for signed integer decimals (passing the wrong type can raise a TypeError). Mismatched numbers of placeholders vs arguments also raise TypeError. Use %% to emit a literal percent sign, and use %(name)s / %(name)d when you want named mapping (dictionary) substitution. Also watch the "single value vs tuple" trap where a lone tuple can be interpreted as the whole argument list; this is one reason newer formatting was introduced. (projects.localizethedocs.org)
Example patterns you can use (short, different from the thread examples):
name = "Bob"
print("as str: %s; as repr: %r; percent: %% " % (name, name))
print("Hello %(name)s — %(n)d items" % {'name': 'Alice', 'n': 3}) (Placeholders must line up with the values you pass; the second line shows dictionary-style substitution.) (projects.localizethedocs.org)
Modern practice: for Python 3.6+ prefer formatted string literals (f-strings) for readability and speed, e.g. f"Hello {name}, you have {n} items". They let you embed expressions and use the same format-mini-language as str.format(). If you maintain code that interfaces with the logging module or older libraries, you will still see %-style formatting used there, so a mix is common in practice. (peps.python.org)
Summary best-practices: use % for quick scripts or when interfacing with APIs that expect it; prefer f-strings in modern code for clarity; validate input types when using %d and always match placeholders to arguments to avoid TypeError.
Jump to Post— Lardmeister 461Here 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]) …
%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.