Python Coding Part-2
[Link]
1) Docstrings provide a convenient way of associating documentation with functions, classes,
methods or modules.
2) They appear right after the definition of a function, method, class, or module.
In [49]: def square(num):
'''Square Function :- This function will return the square of a
number'''
return num**2
In [51]: square(2)
Out[51]: 4
In [52]: square. doc # We can access the Docstring using doc method
Out[52]: 'Square Function :- This function will return the square of a number'
In [53]: def evenodd(num):
'''evenodd Function :- This function will test whether a numbr is
Even or Od
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
In [54]: evenodd(3)
Odd Number
In [55]: evenodd(2)
Even Number
In [56]: evenodd. doc
Out[56]: 'evenodd Function :- This function will test whether a numbr is Even or
Odd'
[Link]
A Python variable is a reserved memory location to store values.A variable is
created the moment you first assign a value to it.
In [75]: p = 30
In [76]: '''
id() function returns the “identity” of the
object. The identity of an object - Is an integer
- Guaranteed to be unique
- Constant for this object during its lifetime.
'''
id(p)
Out[76]: 140735029552432
In [77]: hex(id(p)) # Memory address of the variable
Out[77]: '0x7fff6d71a530'
In [94]: p = 20 #Creates an integer object with value 20 and assigns the variable
p to p
q = 20 # Create new reference q which will point to value 20. p & q will
be poi
r = q # variable r will also point to the same location where p & q are
Out[94]: (20, int, '0x7fff6d71a3f0')
In [95]: q , type(q), hex(id(q))
Out[95]: (20, int, '0x7fff6d71a3f0')
In [96]: r , type(r), hex(id(r))
Out[96]: (20, int, '0x7fff6d71a3f0')
In [146]: p = 20
p = p + 10 # Variable Overwriting
p
Out[146]: 30
Variable Assigment
In [100]: intvar = 10 # Integer variable
floatvar = 2.57 # Float Variable
strvar = "Python Language" # String variable
print(intvar)
print(floatvar)
print(strvar)
10
2.57
Python Language
Multiple Assignments
In [102]: intvar , floatvar , strvar = 10,2.57,"Python Language" # Using commas to
separat
print(intvar)
print(floatvar)
print(strvar)
10
2.57
Python Language
In [105]: p1 = p2 = p3 = p4 = 44 # All variables pointing to same value
print(p1,p2,p3,p4)
44 44 44 44
[Link] Types
Numeric
In [135]: val1 = 10 # Integer data type
print(val1)
print(type(val1)) # type of object
print([Link](val1)) # size of integer object in bytes
print(val1, " is Integer?", isinstance(val1, int)) # val1 is an instance
of int
10
<class
'int'> 28
10 is Integer? True
In [126]: val2 = 92.78 # Float data type
print(val2)
print(type(val2)) # type of object
print([Link](val2)) # size of float object in bytes
print(val2, " is float?", isinstance(val2, float)) # Val2 is an instance
of floa
92.78
<class
'float'> 24
92.78 is float? True
In [136]: val3 = 25 + 10j # Complex data type
print(val3)
print(type(val3)) # type of object
print([Link](val3)) # size of float object in bytes
print(val3, " is complex?", isinstance(val3, complex)) # val3 is an
instance of
(25+10j)
<class
'complex'> 32
(25+10j) is complex? True
In [119]: [Link](int()) # size of integer object in bytes
Out[119]: 24
In [120]: [Link](float()) # size of float object in bytes
Out[120]: 24
In [138]: [Link](complex()) # size of complex object in bytes
Out[138]: 32
Boolean
Boolean data type can have only two possible values true or false.
In [139]: bool1 = True
In [140]: bool2 = False
In [143]: print(type(bool1))
<class 'bool'>
In [144]: print(type(bool2))
<class 'bool'>
In [148]: isinstance(bool1, bool)
Out[148]: True
In [235]: bool(0)
Out[235]: False
In [236]: bool(1)
Out[236]: True
In [237]: bool(None)
Out[237]: False
In [238]: bool (False)
Out[238]: False
[Link]
String Creation
In [193]: str1 = "HELLO PYTHON"
print(str1)
HELLO PYTHON
In [194]: mystr = 'Hello World' # Define string using single quotes
print(mystr)
Hello World
In [195]: mystr = "Hello World" # Define string using double quotes
print(mystr)
Hello World
In [196]: mystr = '''Hello
World ''' # Define string using triple quotes
print(mystr)
Hello
World
In [197]: mystr = """Hello
World""" # Define string using triple quotes
print(mystr)
Hello
World
In [198]: mystr = ('Happy '
'Monday '
'Everyone')
print(mystr)
Happy Monday Everyone
In [199]: mystr2 = 'Woohoo '
mystr2 = mystr2*5
mystr2
Out[199]: 'Woohoo Woohoo Woohoo Woohoo Woohoo '
In [200]: len(mystr2) # Length of string
Out[200]: 35
String Indexing
In [201]: str1
Out[201]: 'HELLO PYTHON'
In [202]: str1[0] # First character in string "str1"
Out[202]: 'H'
In [203]: str1[len(str1)-1] # Last character in string using len function
Out[203]: 'N'
In [204]: str1[-1] # Last character in string
Out[204]: 'N'
In [205]: str1[6] #Fetch 7th element of the string
Out[205]: 'P'
In [206]: str1[5]
Out[206]: ' '
String Slicing
In [207]: str1[0:5] # String slicing - Fetch all characters from 0 to 5 index
location exc
Out[207]: 'HELLO'
In [208]: str1[6:12] # String slicing - Retreive all characters between 6 - 12
index loc e
Out[208]: 'PYTHON'
In [209]: str1[-4:] # Retreive last four characters of the string
Out[209]: 'THON'
In [210]: str1[-6:] # Retreive last six characters of the string
Out[210]: 'PYTHON'
In [211]: str1[:4] # Retreive first four characters of the string
Out[211]: 'HELL'
In [212]: str1[:6] # Retreive first six characters of the string
Out[212]: 'HELLO '
Update & Delete String
In [213]: str1
Out[213]: 'HELLO PYTHON'
In [214]: #Strings are immutable which means elements of a string cannot be changed
once t
str1[0:5] = 'HOLAA'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-214-ea670ff3ec72> in <module>
1 #Strings are immutable which means elements of a string cannot be chang ed once they have been assigned.
----> 2 str1[0:5] = 'HOLAA'
TypeError: 'str' object does not support item assignment
In [215]: del str1 # Delete a string
print(srt1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-215-7fcc0cc83dcc> in <module>
1 del str1 # Delete a string
----> 2 print(srt1)
NameError: name 'srt1' is not defined
String concatenation
In [216]: # String concatenation
s1 =
"Hello" s2
= "Asif" s3
= s1 + s2
print(s3)
HelloAsif
In [217]: # String concatenation
s1 =
"Hello" s2
= "Asif"
s3 = s1 + " " + s2
print(s3)
Hello Asif
Iterating through a String
In [218]: mystr1 = "Hello Everyone"
In [219]: # Iteration
for i in mystr1:
print(i)
H
e
E
v
In [220]: for i in enumerate(mystr1):
print(i)
(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
(5, ' ')
(6, 'E')
(7, 'v')
(8, 'e')
(9, 'r')
(10, 'y')
(11, 'o')
(12, 'n')
(13, 'e')
In [221]: list(enumerate(mystr1)) # Enumerate method adds a counter to an iterable
and ret
Out[221]: [(0, 'H'),
(1, 'e'),
(2, 'l'),
(3, 'l'),
(4, 'o'),
(5, ' '),
(6, 'E'),
(7, 'v'),
(8, 'e'),
(9, 'r'),
(10, 'y'),
(11, 'o'),
(12, 'n'),
(13, 'e')]
String Membership
In [222]: # String membership
mystr1 = "Hello Everyone"
print ('Hello' in mystr1) # Check whether substring "Hello" is present in
string print ('Everyone' in mystr1) # Check whether substring "Everyone"
is present in print ('Hi' in mystr1) # Check whether substring "Hi" is
present in string "mysr
True
True
Fals
e
String Partitioning
In [256]: """
The partition() method searches for a specified string and splits the
string int
- The first element contains the part before the argument string.
- The second element contains the argument string.
- The third element contains the part after the argument
string. """
str5 = "Natural language processing with Python and R and
Java" L = [Link]("and")
print(L)
('Natural language processing with Python ', 'and', ' R and Java')
In [257]: """
The rpartition() method searches for the last occurence of the specified
string containing three elements.
- The first element contains the part before the argument string.
- The second element contains the argument string.
- The third element contains the part after the argument
string. """
str5 = "Natural language processing with Python and R and
Java" L = [Link]("and")
print(L)
('Natural language processing with Python and R ', 'and', ' Java')
String Functions
In [267]: mystr2 = " Hello Everyone "
mystr2
Out[267]: ' Hello Everyone '
In [268]: [Link]() # Removes white space from begining & end
Out[268]: 'Hello Everyone'
In [270]: [Link]() # Removes all whitespaces at the end of the string
Out[270]: ' Hello Everyone'
In [269]: [Link]() # Removes all whitespaces at the begining of the string
Out[269]: 'Hello Everyone '
In [272]: mystr2 = "*********Hello Everyone***********All the
Best**********" mystr2
Out[272]: '*********Hello Everyone***********All the Best**********'
In [273]: [Link]('*') # Removes all '*' characters from begining & end of the
string
Out[273]: 'Hello Everyone***********All the Best'
In [274]: [Link]('*') # Removes all '*' characters at the end of the string
Out[274]: '*********Hello Everyone***********All the Best'
In [275]: [Link]('*') # Removes all '*' characters at the begining of the
string
Out[275]: 'Hello Everyone***********All the Best**********'
In [276]: mystr2 = " Hello Everyone "
In [277]: [Link]() # Return whole string in lowercase
Out[277]: ' hello everyone '
In [278]: [Link]() # Return whole string in uppercase
Out[278]: ' HELLO EVERYONE '
In [279]: [Link]("He" , "Ho") #Replace substring "He" with "Ho"
Out[279]: ' Hollo Everyone '
In [280]: [Link](" " , "") # Remove all whitespaces using replace function
Out[280]: 'HelloEveryone'
In [281]: mystr5 = "one two Three one two two three"
In [230]: [Link]("one") # Number of times substring "one" occurred in string.
Out[230]: 2
In [231]: [Link]("two") # Number of times substring "two" occurred in string.
Out[231]: 3
In [232]: [Link]("one") # Return boolean value True if string starts
with "one
Out[232]: True
In [233]: [Link]("three") # Return boolean value True if string ends with
"three"
Out[233]: True
In [234]: mystr4 = "one two three four one two two three five five six seven six
seven one
In [235]: mylist = [Link]() # Split String into substrings
mylist
Out[235]: ['one',
'two',
'three',
'four',
'one',
'two',
'two',
'three',
'five',
'five',
'six',
'seven','six','seven','one','one','one','ten','eight','ten','nine','eleven',
'ten','ten','nine']
In [236]: # Combining string & numbers using format method
item1 = 40
item2 = 55
item3 = 77
res = "Cost of item1 , item2 and item3 are {} , {} and {}"
print([Link](item1,item2,item3))
Cost of item1 , item2 and item3 are 40 , 55 and 77
In [237]: # Combining string & numbers using format method
item1 = 40
item2 = 55
item3 = 77
res = "Cost of item3 , item2 and item1 are {2} , {1} and {0}"
print([Link](item1,item2,item3))
Cost of item3 , item2 and item1 are 77 , 55 and 40
In [238]: str2 = " WELCOME EVERYONE "
str2 = [Link](100) # center align the string using a specific
character as
print(str2)
WELCOME EVERYONE
In [239]: str2 = " WELCOME EVERYONE "
str2 = [Link](100,'*') # center align the string using a specific
character
print(str2)
***************************************** WELCOME EVERYONE
********************
*********************
In [240]: str2 = " WELCOME EVERYONE "
str2 = [Link](50) # Right align the string using a specific character
as the
print(str2)
WELCOME EVERYONE
In [241]: str2 = " WELCOME EVERYONE "
str2 = [Link](50,'*') # Right align the string using a specific
character ('
print(str2)
******************************** WELCOME EVERYONE
In [242]: str4 = "one two three four five six seven"
loc = [Link]("five") # Find the location of word 'five' in the string
"str4"
print(loc)
19
In [243]: str4 = "one two three four five six seven"
loc = [Link]("five") # Find the location of word 'five' in the string
"str4"
print(loc)
19
In [244]: mystr6 = '123456789'
print([Link]()) # returns True if all the characters in the text
are let print([Link]()) # returns True if a string contains only
letters or num print([Link]()) # returns True if all the
characters are decimals (0-9 print([Link]()) # returns True if
all the characters are numeric (0-9)
Fals
e
True
True
True
In [245]: mystr6 = 'abcde'
print([Link]()) # returns True if all the characters in the text
are let print([Link]()) # returns True if a string contains only
letters or num print([Link]()) # returns True if all the
characters are decimals (0-9 print([Link]()) # returns True if
all the characters are numeric (0-9)
True
True
Fals
e
Fals
e
In [246]: mystr6 = 'abc12309'
print([Link]()) # returns True if all the characters in the text
are let print([Link]()) # returns True if a string contains only
letters or num print([Link]()) # returns True if all the
characters are decimals (0-9 print([Link]()) # returns True if
all the characters are numeric (0-9)
False
True
Fals
e
Fals
e
In [247]: mystr7 = 'ABCDEF'
print([Link]() # Returns True if all the characters are in upper case
)
print([Link]() # Returns True if all the characters are in lower case
)
True
Fals
e
In [248]: mystr8 = 'abcdef'
print([Link]() # Returns True if all the characters are in upper case
)
print([Link]() # Returns True if all the characters are in lower case
)
Fals
e
True
In [258]: str6 = "one two three four one two two three five five six one ten eight
ten nin
loc = [Link]("one") # last occurrence of word 'one' in string "str6"
print(loc)
51
In [259]:
loc = [Link]("one") # last occurrence of word 'one' in string "str6"
print(loc)
51
In [264]: txt = " abc def ghi "
[Link]()
Out[264]: ' abc def ghi'
In [265]: txt = " abc def ghi "
[Link]()
Out[265]: 'abc def ghi '
In [266]: txt = " abc def ghi "
[Link]()
Out[266]: 'abc def ghi'
Using Escape Character
In [252]: #Using double quotes in the string is not allowed.
mystr = "My favourite TV Series is "Game of Thrones""
File "<ipython-input-252-0fa35a74da86>", line 2
mystr = "My favourite TV Series is "Game of Thrones""
^
SyntaxError: invalid syntax
In [253]: #Using escape character to allow illegal
characters mystr = "My favourite series is
\"Game of Thrones\"" print(mystr)
My favourite series is "Game of Thrones"