In [1]:
#String Formatting
#str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting
In [1]:
#Dictionary
person={'name':'John','age':30}
In [8]:
sentence='My name is ' + person['name'] + ' and i am ' + str(person['age']) + ' yrs old.'
print(sentence)
My name is John and i am 30 yrs old.
In [12]:
#Above code using format method
sentence='My name is {} and i am {} yrs old.'.format(person['name'],person['age'])
print(sentence)
My name is John and i am 30 yrs old.
In [16]:
tag='h1'
text="This is a Heading"
In [17]:
sentence='<{0}>{1}<\{0}>'.format(tag,text)
print(sentence)
<h1>This is a Heading<\h1>
In [20]:
sentence='My name is {0[name]} and i am {0[age]} yrs old.'.format(person)
print(sentence)
My name is John and i am 30 yrs old.
In [22]:
class Person():
    
    def __init__(self,name,age):
        self.name=name
        self.age=age
        
p1 = Person("Aron",25)

sentence='My name is {0.name} and i am {0.age} yrs old.'.format(p1)
print(sentence)
My name is Aron and i am 25 yrs old.
In [23]:
sentence='My name is {name} and i am {age} yrs old.'.format(name='ken',age=24)
print(sentence)
My name is ken and i am 24 yrs old.
In [24]:
person={'name':'John','age':30}
In [25]:
#Best way to unpack a dictionary
sentence='My name is {name} and i am {age} yrs old.'.format(**person)
print(sentence)
My name is John and i am 30 yrs old.
In [26]:
for i in range(1,11):
    sentence="The Value is {}".format(i)
    print(sentence)
The Value is 1
The Value is 2
The Value is 3
The Value is 4
The Value is 5
The Value is 6
The Value is 7
The Value is 8
The Value is 9
The Value is 10
In [27]:
#To Print numbers in 2 digit only
for i in range(1,11):
    sentence="The Value is {:02}".format(i)
    print(sentence)
The Value is 01
The Value is 02
The Value is 03
The Value is 04
The Value is 05
The Value is 06
The Value is 07
The Value is 08
The Value is 09
The Value is 10
In [29]:
pi =3.14159265
sentence="Value of pi is {:.2f}".format(pi)
print(sentence)
Value of pi is 3.14
In [32]:
sentence="1MB is equal to {} bytes".format(1000**2)
print(sentence)
1MB is equal to 1000000 bytes
In [33]:
sentence="1MB is equal to {:,} bytes".format(1000**2)
print(sentence)
1MB is equal to 1,000,000 bytes
In [34]:
sentence="1MB is equal to {:,.2f} bytes".format(1000**2)
print(sentence)
1MB is equal to 1,000,000.00 bytes
In [35]:
import datetime
my_date = datetime.datetime(2016,9,24,12,30,45)
print(my_date)
2016-09-24 12:30:45
In [36]:
sentence='{:%B %d, %Y}'.format(my_date)
print(sentence)
September 24, 2016
In [40]:
#September 24, 2016 fell on a Saturday and was the 268 day of the year.
sentence="{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year.".format(my_date)
print(sentence)
September 24, 2016 fell on a Saturday and was the 268 day of the year.