In [ ]:
print("Hello")
In [ ]:
# Strings are immutable types, once created we can not modify a string. Any operation on string will result
# in a new string
country = "India"
# strings are stored as lists (non-mutable), we can access each character by its index
print(country[0])
print(country[1])
In [ ]:
# We can iterate over each element in string by index
for character in country:
print(character, end='-') # Using end as an argument print acts as a de-limiter and prints
# the characters accordingly
In [ ]:
user = input("Enter username: ")
'Hello user: {}'.format(user)
In [1]:
# Raw formatting
'Numbers are {} {}'.format(1,2)
Out[1]:
In [3]:
# Formatting with index of arguments, an option to change placeholders !
'Numbers are {1} {0}'.format(6,7)
Out[3]:
In [6]:
'{:>10}'.format('test')
Out[6]:
In [7]:
'{:<10}'.format('test')
Out[7]:
In [8]:
'{:10}'.format('test')
Out[8]:
In [9]:
'{:_<10}'.format('test')
Out[9]:
In [15]:
'{:_>10}'.format('test')
Out[15]:
In [12]:
'{:^10}'.format('test')
Out[12]:
In [17]:
'{:_^10}'.format('test')
Out[17]:
In [22]:
'{:.5}'.format('xylophone')
Out[22]:
In [23]:
'{:10.5}'.format('xylophone')
Out[23]:
In [29]:
'{:_<10.5}'.format('xylophone')
Out[29]:
In [26]:
'{:_>10.5}'.format('xylophone')
Out[26]:
In [30]:
'{:d}'.format(42) #Ints
Out[30]:
In [31]:
'{:f}'.format(3.141592653589793)
Out[31]:
In [32]:
# Padding numbers
'{:4d}'.format(42)
Out[32]:
In [33]:
'{:04d}'.format(42)
Out[33]:
In [34]:
# Padding and truncating float
'{:06.2f}'.format(3.141592653589793)
Out[34]:
In [41]:
# Signing numbers
'{:+d}'.format(42)
Out[41]:
In [42]:
'{:d}'.format(-42)
Out[42]:
In [49]:
# Placeholders
data = {'name': 'John', 'password': 'john123'}
print('Username is {name} and password is {password}'.format(**data))
print('Username is {name} and password is {password}'.format(name='Opensource',password='Welcome'))
In [50]:
person = {'first': 'Hello', 'last': 'User'}
'{p[first]} {p[last]}'.format(p=person)
Out[50]:
In [51]:
data = [4, 8, 15, 16, 23, 42]
'{d[4]} {d[5]}'.format(d=data)
Out[51]:
In [52]:
class Plant(object):
type = 'tree'
'{p.type}'.format(p=Plant())
Out[52]:
In [53]:
class Plant(object):
type = 'tree'
kinds = [{'name': 'oak'}, {'name': 'maple'}]
'{p.type}: {p.kinds[0][name]}'.format(p=Plant())
Out[53]:
In [54]:
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Out[54]:
In [2]:
# Single quotes
'Isn\'t'
Out[2]:
In [3]:
"Isn't"
Out[3]:
In [ ]: