Example 1: how to use %s python
'%s is the true joke' % args
Example 2: formatting in python
# There are 3 different types of formatting.
>>> name = "John"
>>> age = 19
>>> language = "python"
>>> print(f"{name} of age {age} programs in {language}") # Commonly used.
John of age 19 programs in python
>>> print("%s of age %d programs in %s" %(name, age, language)) # %s for str(), %d for int(), %f for float().
John of age 19 programs in python
>>> print("{} of age {} programs in {}".format(name, age, language)) # Values inside .format() will be placed inside curly braces repectively when no index is specified.
John of age 19 programs in python
>>> print("{2} of age {1} programs in {0}".format(name, age, language)) # Index can be specified inside of curly braces to switch the values from .format(val1, val2, val3).
python of age 19 programs in John
Example 3: python format specifier
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Example 4: python format string with list
>>> print('Skillset: {}'.format(*langs))
Skillset: C
Example 5: python %d
# %s is used as a placeholder for string values you want to inject
# into a formatted string.
# %d is used as a placeholder for numeric or decimal values.
# For example (for python 3)
print ('%s is %d years old' % ('Joe', 42))
# Would output
>>>Joe is 42 years old
Example 6: %s %d python
name = "Gandalf"
extendedName = "the Grey"
age = 84
IQ = 149.9
print('type(name):', type(name)) #type(name):
print('type(age):', type(age)) #type(age):
print('type(IQ):', type(IQ)) #type(IQ):
print('%s %s\'s age is %d with incredible IQ of %f ' %(name, extendedName, age, IQ)) #Gandalf the Grey's age is 84 with incredible IQ of 149.900000
#Same output can be printed in following ways:
print ('{0} {1}\'s age is {2} with incredible IQ of {3} '.format(name, extendedName, age, IQ)) # with help of older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ)) # with help of older method
print("Multiplication of %d and %f is %f" %(age, IQ, age*IQ)) #Multiplication of 84 and 149.900000 is 12591.600000
#storing formattings in string
sub1 = "python string!"
sub2 = "an arg"
a = "i am a %s" % sub1
b = "i am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print(a) # "i am a python string!"
print(b) # "i am a python string!"
print(c) # "with an arg!"
print(d) # "with an arg!"