Saturday, December 28, 2019

Python list statements

If we want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then we should go for list.
Insertion order preserved 
Duplicate objects are allowed
Heterogeneous objects are allowed 
List is dynamic because based on our requirement we can increase the size and descrease the size.
In list the elements will be placed within square brackets and with comma separator.
We can differentiate duplicate elements by using index and we can preserve insertion order by using index.Hence index will play very important role.
Python supports both positive and negative indexes. +ve index means from left to right where as negative index means right to left

-6                                -5                              - 4                             -3                              -2                              -1
10
A
B
20
30
10

0                                  1                               2                                3                               4                                5

[10,”A”,”B”,20,30,10]

List objects are mutable. i.e we can change the content.

Creation of list objects:

We can create empty list objects as follows 

list[]
print(list)
print(type(list))

[]
<class ‘list’>

If we know elements already then we can create list as follows list = [10,20,30,40]

With dynamic input:

list=eval(input(“Enter List:”))
print(list)
print(type(list))

D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10,20,30,40]
<class ‘list’>

With list() function:

l=list(range(0,10,2))
print(l)
print(type(l))

D:\Python_classes>py test.py
[0,2,4,6,8]
<class ‘list’>

Eg:

s=“karth”
l=list(s)
print(l)

D:\Python_classes>py test.py
[‘k’,’a’,’r’,’t’,’h’]

With split() function:

s=“Learning Python is very very easy !!!”
l=s.split()
print(l)
print(type(l))

D:\Python_classes>py test.py
[‘Learning’, ‘Python’, ‘is’, ‘very’, ‘very’, ‘easy’, ‘!!!’]
<class ‘list’>

Note: sometimes we can take list inside another list, such type of lists are called nested lists

[10,20, [30, 40]]

Accessing elements of list:

We can access elements of the list either by using index or by using slice operator(:)

By using index:

List follows zero based index, ie index of first element is zero 
List supports both +ve and -ve indexes 
+ve index meant for left to right
-ve index meant for right to left 
list = [10,20,30,40]

-4                                -3                              -2                            -1
10
20
30
40
0                                  1                                2                               3

print(list[0]) —> 10
print(list[-1]) —> 40
print(list[10]) —> IndexError: list index out of range.

By using Slice operator 

Syntax: list2 = list1[start:stop:step]

Start: It indicates the index where slice has to Start  [ Default Value is 0 ]
Stop: It indicates the index where slice has to End [ Default value is max allowed index of List ie Length of the List ]
Step: increment value [ Default value is 1 ] 

n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])

Output:

D:\Python_classes>py test.py

[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]

List vs Mutability 

Once we creates a List Object, we can modify its content. Hence List objects are mutable.

n=[10,20,30,40]
print(n)
n[1]=777
print(n)

D:\Python_classes>py test.py
[10,20,30,40]
[10,777,30,40]

Traversing the elements of list:

The sequential access of each element in the list is called traversal 

By using while loop: 

n = [0,1,2,3,4,5,6,7,8,9,10]
i = 0 
while l < len(n):
print(n[i])
i=I+1

D:\Python_classes>py test.py

0
1
2
3
4
5
6
7
8
9
10

By using for Loop:

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)

D:\Python_classes>py test.py

0
1
2
3
4
5
6
7
8
9
10

To display only even numbers 

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if  n1%2==0:
print(n1)

D:\Python_classes?py test.py
0
2
4
6
8
10

To display elements by index wise:

l = [“A”,”B”,”C”]
x = len(l)
for i in range(x):
print(l[I],”is available at positive index: “,I, “and negative index: “,I-x)

D:\Python_classes>py test.py

A is available at positive index: 0 and at negative index: -3 
A is available at positive index: 1 and at negative index: -2
A is available at positive index: 2 and at negative index: -1

Important function of list:

To get information about List:

len() : returns the number of elements present in the list 

Eg: n = [10,20,30,40]

print(len(n)) —> 4

count() : it returns the number of occurrences of specified item in the list.

n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

D:\Python_classes>py test.py

1
4
2
0

index(): returns the index of first occurrence of the specified item.

n=[1,2,2,2,2,3,3]

print(n.index(1)) —> 0
print(n.index(2)) —> 1
print(n.index(3)) —> 5
print(n.index(4)) —> ValueErrorL 4 is not in list 

Note: if the specified element not present in the list then we will get ValueError. Hence before index() method we have to check whether item present in the list or not using in operator.

print(4 in n) —> False 

Manipulating Elements of List:

append() Function:

We can use append() function to add item at the end of the list.

list=[]
list.append(“A”)
list.append(“B”)
list.append(“C”)
print(list)

D:\Python_classes>py test.py
[‘A’,’B’,’C’]

To add all elements to list upto 100 which are divisible by 10

list=[]
for I in range(101):
if I%10==0:
list.append(i)
print(list)

D:\Python_classes>py test.py
[0,10,20,30,40,50,60,70,80,90,100]

Insert() function 

To insert item at specified index position 

n=[1,2,3,4,5]
n.insert(1,888)
print(n)

D:\Python_classes>py test.py
[1,888,2,3,4,5]

n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)

D:\Python_classes>py test.py
[999,1,2,3,4,5,777]

Note: if the specified index is greater than max index then element will be inserted at last position. If the specified index is smaller than min index then element will be inserted at first position.

Differences between append() and insert() 


Append() 
Insert()
In list when we add any element it will come in last i.e it will be last element.
In list we can insert any element in particular index number 

Extend () function 

To add all items of one list to another list.

l1.extend(l2)

All items present in l2 will be added to l1 

order1=[“Chicken”,”Mutton”,”Fish”]
order2=[“RC”,”KF”,”FO”]
order1.extend(order2)
print(order1)

D:\Python_classes>py test.py
['Chicken','Mutton','Fish','RC','KF','FO’]

order = [“Chicken”,”Mutton”,”Fish”]
order.extend(“Mushroom”)
print(order)

D:\Python_classes>py test.py
['Chicken','Mutton','Fish’,’m’,’u’,’s’,’h’,’r’,’o’,’o’,’m’]

Remove() function 

We can use this function to remove specified item from the list. If the item present multiple times then only first occurrence will be removed.

n=[10,20,10,30]
n.remove(10)
print(n)

D:\Python_classes>py test.py
[20,10,30]

If the specified item not present in list then we will get ValueError

n=[10,20,10,30]
n.remove(40)
print(n)

ValueError: list.remove(x): x nit in list 

Note: Hence before using remove() method first we have to check specified element present in the list or not by using in operator.

pop() function:

It removes and returns the last element of the list 
This is only function which manipulates list and returns some element.

n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

D:\Python_classes>py test.py
40
30
[10,20]

If the list is empty then pop() function IndexError

n = []
print(n.pop()) —> IndexError: pop from empty list 

Note: 

pop() is only function which manipulates the list and returns some value
In general we can use append() and pop() functions to implement stack datastructure by using list, which follows LIFO ( last in first out ) order.

In general we can use pop() function to remove  last element of the list. But we can use to remove elements based on index.

n.pop(index) —> to remove and return element present at specified index
n.pop()  —> to remove and return last element of the list 

n = [10,20,30,40,50,60]
print(n.pop()) —> 60 
print(n.pop(1)) —> 20 
print(n.pop(10)) —> IndexError: pop index out of range.

Difference b/w remove() and pop()


Remove() 
pop()
We can use to remove special element from the list 
We can use to remove last element from the list
It cannot return value 
It returned removed element
If special element not available then we get VALUE ERROR
If list is empty then we get error

Note: List objects ate dynamic i.e based on our requirement we can increase and decrease the size.

append(), insert(), extend(), —> for increasing the size/growable nature.
Remove(), pop() —> for decreeing the size/shrinking nature.

Ordering elements of list 

reverse(): we can use to reverse()  order of elements of list.

n=[10,20,30,40]
n.reverse()
print(n)

D:\Python_classes>py test.py
[40,30,20,10]

Sort():  in list by default insertion order is preserved, if want to sort the elements of list according to default natural sorting order then we should go for the sort() method.

For numbers —> Default natural sorting order is ascending order 
For Strings:  Default natural sorting order is alphabetical order 

n = [20,5,15,10,0]
n.sort()
print(n) —> [0,5,10,15,20]

s = [“Dog”,Banana”,”Cat”,”Apple”]
s.sort()
print(s) —> [‘Apple’,’Banana’,’Cat’,’Dog’]

Note: to use sort() function, compulsory list should contain only homogenous elements, otherwise we will get typeerror

n = [20,10,”A”,”B”]
n.sort()
print(n)

TypeError: ‘<‘ not supported b/w instances of ’str’ and ‘int’

Note: In python 2 if list contains both numbers and strings then sort(0 function first sort numbers  followed by strings

n=[20,”B”,10,”A”]
n.sort()
print(n) # [10,20,’A’,’B’]

But in python 3 it is invalid 

To sort in reverse of default natural sorting order:

We can sort according to reverse of default natural sorting order by using reverse=True argument.

n = [40,10,30,20]
n.sort()
print(n) —> [10,20,30,40]
n.sort(reverse = True)
print(n) —> [40,30,20,10]
n.sort(reverse = False)
print(n) —> [10,20,30,40]

Aliasing and cloning of list objects:

The process of giving another reference variable to the existing list is called aliasing.

10 
20
30
40
x  y 

x=[10,20,30,40]
y=x
print(id(x))
print(id(y))

The problem in this approach is by using one reference variable if we are changing content , then those changes will be reflected to the other reference variable.


10
20 ( crossed)
30
4
                                       177

x = [10,20,30,40]
y = x
Y[1] = 777

print(x)  —> [10,777,30,40]

To overcome this problem we should go for cloning.
The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function.

By using slice operator 

x = [10,20,30,40]
y = x[:]
y[1] = 777
print(x) —> [10,20,30,40]
print(y) —> [10,777,30,40]


10
20
30
40
(x)


10
20 (crossed)
30
40
                                      777 

(y)

Difference b/w = Operator and copy() function 

= operator meant for aliasing 
copy() function meant for cloning

Using Mathematical operator for list objects 

[ we can use + and * operators for list objects ].

Concatenation operator (+):

We can use + to concatenate 2 lists into a single list.

a=[10,20,30]
b=[40,50,60]
c = a+b
print(c) —> [10,20,30,40,50,60]

Note: to use + operator compulsory both arguments should be list objects , otherwise we will get TypeError.

c = a+40 —> TypeError: can only concatenate list ( not “int”) to list.
c = a+[40] —> valid 

Repetition operator(*):

We can use repetition operator (*) to repeat elements of list specified number of times.

x = [10,20,30]
y = x*3
print(y) —> [10,20,30,10,20,30,10,20,30]

Comparing List objects 

We can use comparison operators for list objects.















Friday, December 27, 2019

How to switch to different azure subscritption using powershell GET approach

Mac setup

Steps for Mac OS ( 10.2 or newer )

Install brew
Install Powershell Core ( brew cask install powershell )
Update brew and powershell ( brew update  ; brew cask install powershell ).
Install Azure Module ( pwsh  ps> Install-Module -Name Az -AllowClobber )
Install PSPKI ( for New-SelfSignedCertificateEx )
ps> Install-Module -Name PSPKI
ps> Import-Module -Name PSPKI

How to connect to the azure subscription using the Az powershell module ?

Install-Module -Name Az -AllowClobber

Then issue command:

Connect-AzAccount

WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code FS5V4TL99 to authenticate. ] 

New-AzResourceGroup -Name $resourcegroupname -Location $location

How to test the connectivity with that subscription ?

Get-AzVirtualBetworkGateway -Name <name of VPN gateway>  -ResourceGroupName <Resource group>

when you switch the subscription, need to follow these steps 

Uninstall-AzureRm

Install-Module -Name Az -AllowClobber


Then issue command:
Connect-AzAccount
New-AzResourceGroup -Name $resourcegroupname -Location $location

Thursday, December 26, 2019

String data type


The most commonly used object in any project and in any programming language is String only. Hence we should aware complete information about string data type.

What is string ?
Any sequence of characters within either single quotes or double quotes is considered as a string.

Syntax:

s = ‘karthik’
s = “karthik”

Note: In most of other languages like C, C++, Java a single character with in single quotes is treated as char data type value. But in python we are not having char datatype. Hence it is treated as String only.

Eg: 

>>> ch = ‘a’
>>> type(ch)
<class ’str’>

How to define multi-line string literals ?
We can define multi-line string literals by using triple single or double quotes 

Eg:
>>> s = ‘’’karthik
testing
solutions’'' 

We can also use triple quotes to use single quotes or double quotes as symbol  inside string literal

s = ’This is ’single quote symbol’ —> invalid
s = ’This is \’ single quote symbol’ —> valid 
s = “This is ’single quote symbol” —> valid 
s = ’This is “ double quotes symbol’ —> valid 
s = ’The “Python Notes” by ‘karthik’ is very helpful’ —> invalid 
s = “The “Python Notes” by ‘karthik’ is very helpful” —> invalid 
s = ’The \”Python Notes\” by \’karthik\’ is very helpful’ —> valid 
s = ‘’’The  “Python Notes” by ‘durga’ is very helpful’’’ —> valid 

How to Access characters of a string ?

We can access characters of a string by using the following ways.
By using index 
By using slice operator 

Accessing characters by using index:

Python supports both +ve and -ve index 

+ve index means left to right ( forward direction )
-ve index means right to left ( backward direction )

Eg:  s = ‘karthik’

>>> s=‘karth’
>>> s[0]
‘k’
>>> s[4]
h’
>>> s[-1]
‘h’
>>> s[10]
indexError: string index out of range 

Note: if we are trying to access characters of a string with out of range index then we will get error saying: IndexError

Write a program to accept some string from the keyboard and display its characters by index wise ( both positive and negative index) 

test.py

s=input(“Enter some string:”)
i=0
for x in s:
print(“The character present at positive index {} and at negative index {} is {}” .format(I,i-len(s),x))
i=i+1

Output: 
D:\python_classes>py test.py

Enter Some String:karth

The character present at positive index 0 and at negative index -5 is k
The character present at positive index 1 and at negative index -4 is a
The character present at positive index 2 and at negative index -3 is r
The character present at positive index 3 and at negative index -2 is t
The character present at positive index 4 and at negative index -1 is h

Accessing characters by using slice operator: 

Syntax: s[bEginindex:endindex:step]

Begin Index: From where we have to consider slice (substring)
End Index: we have to terminate the slice (substring) at endindex-1
Step: Incremented Value

Note: 

If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string.
The default value for step is 1 

>>> s=“Learning Python is very very easy!!!”
>>> s[1:7:1]
‘earnin’
>>> s[1:7]
‘earnin’
>>> s[1:7:2]
‘eri’
>>> s[:7]
‘Learnin’
>>> s[7:]
‘g Python is very very easy!!!’
>>> s[::]
‘Learning Python is very very easy!!!’
>>> s[:]
‘Learning Python is very very easy!!!’
>>> s[::-1]
‘!!!ysae yrev yrev si nohtyp gninraeL’

Behavior of slice operator:

s[bEgin:end:step]
Step value can be either +ve or -ve 
If +ve then it should be forward direction(left to right) and we have to consider bEgin to end -1 
If -ve then it should be backward direction(right to left) and we have to consider bEgin to end +1 

Note:

In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.

In forward direction:

default value for bEgin: 0
default value for end: length of string
default value for step: +1 

In Backward Direction :

default value for bEgin: -1 
default value for end: -(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and end index.

Slice operator case study  

S = ‘abcdefghij’
s[1:6:2]  —> ‘bdf’
s[::1] —>  ‘abcdefghij’
s[::-1] —> ‘jihgfedcba’
S[3:7:-1] —> ‘'
s[7:4:-1] —> ‘hgf’
s[0:10000:1] —> ‘abcdefghij’
s[-4:1:-1] —> ‘gfedc’
s[-4:1:-2] —> ‘gec’
s[5:0:1] —> ‘'
s[9:0:0] —> ValueError: slice step cannot be zero 
s[0:-10:-1]  —> ‘'
s[0:-11:-1] —> ‘a’
s[0:0:1] —> ‘'
s[0:-9:-2] —> ‘'
s[-5:-9:-2] —> ‘fd’
s[10:-1:-1] —> ‘'
s[10000:2:-1] —> ‘jihgfed’

Note: Slice operator never raises IndexError

Mathematical operations for string:

We can apply the following mathematical operators for strings.

Operators for concatenation 
Operators for repetition 

print(“karth”+”ik”) —> karthik 
print(“karthik”*2) —> karthikkarthik 

Note:
To use + operator for strings, compulsory both arguments should be str type.
To use * operator for strings , compulsory one argument should be str and other argument should be int

len() in-built function 

We can use len() function to find the number of characters present in the string.

Eg: 

s = ‘kaushik’
print(len(s))  —> 5 

Write a program to access each character of sting in forward and backward direction using while loop ?

s = “Learning Python is very easy!!!”
n = len(s) 
i = 0
print(“Forward direction”)
while I<n:
print(s[I], end=‘ ‘)
i +=1
print(“Backward direction”)
i = -1
while i >=-n:
print(s[I],end=‘ ‘)
i = i-1
  
Alternative ways 

s = “Learning Python is very easy !!!”
print(“Forward direction”)
for i in s:
print(I,end=‘ ‘)
print(“Forward direction”)
for I in s[::]:
print(I,end=‘ ‘)

print(“Backward direction”)
for I in s[::-1]:
print(I,end=‘ ‘)

Checking Membership:

We can check whether the character or string is the member of another string or not by using in and not in operators

s = ‘karth’
print(‘k’ in s) —> True 
print(‘2’ in s) —> False 

s = input(“Enter main string:”)
subs = input(“Enter sub string:”)
if subs in s:
   print(subs, “is found in main string”)
else:
   print(subs, “is not found in main string”)

Output:

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:karth
karth is found in main string

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:python
karth is not found in main string

Comparison of strings:

We can use comparison operators  (<,<=,>,>=)  and equality operators  (==, !=) for strings.
Comparison will be performed based on alphabetical order 

s1=input(“Enter first string:”)
s2=input(“Enter Second string:”)
if s1==s2:
print(“Both strings are equal”)
elif s1<s2:
print(“First String is less than Second String”)
else:
print(“First String is greater than Second String”)

Output:

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:karth
Both strings are equal 

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:ravi
Both strings is less than Second String

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:anil
Both strings is greater than Second String

Removing Spaces from the string:

We can use the following 3 methods 

rstrip()  —> To remove spaces at right hand side 
lstrip() —> To remove spaces at left hand side
strip() —> To remove spaces both sides 

city=input(“Enter your city Name:”)
scity=city.strip()
If scity==‘Hyderabad’:
print(“Hello Hyderabad..Adab”)
elif scity==‘Chennai’:
print(“Hello Madrasi…Vanakkam”)
elif scity==“Bangalore”:
print(“Hello kannadiga..shubhodaya”)
else:
print(“your entered city is invalid”)

Finding Substrings:

We can use the following 4 methods 

For Forward direction:

  1. Find()
  2. index()

For Backward direction:

  1. rfind()
  2. rindex()

find():

s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get  -1.

s=“learning Python is very easy”
print(s.find(“Python”)) #9
print(s.find(“Java”)) #-1
print(s.find(“r”))#3
print(s.rfind(“r”))#21

Note: By default find() method  can search total string. We can also specify the boundaries to search.

s.find(substring, bEgin,end)
It will always search from bEgin index to end -1 index.

s=“karthravipavanshiva”
print(s.find(‘a’))#4
print(s.find(‘a’,7,15))#10
print(s.find(‘z’,7,15))#-1

index():

Index() method is exactly same as find()  method except that if the specified substring is not available then we will get valueerror

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
try:
n=s.index(subs)
except  ValueError:
print(“substring not found”)
else:
print(“substring found”)

Output
 
D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:python 
substring found 

D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:java
Substring not  found 

Program to display all positions of substring in a given main string 

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print(“Found at position”,pos)
flag=True
If flag==False:
print(“Not Found”)

Output 

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:bb
Found at position 1 

Counting substring in the given string:

We can find the number of occurrences of substring present in the given string by using count() method 

  1. s.count(substring) —> it will search through out the string 
  2. s.count(substring, bEgin, end) —> it will search from bEgin index to end -1 index.

s=“abcabcabcabcadda”
print(s.count(‘a’))
print(s.count(‘ab’))
print(s.count(‘a’,3,7))

Output 

6
4
2

Replacing a string with another string:

s.replace(old string, newstring)
Inside s, every occurrence of old string will be replaced with new string.

Eg1

s = “Learning Python is very difficult”
s1 = s.replace(“difficult”, “easy”)
print(s1)

Output :  Learning Python is very easy

Eg2: All occurrences will be replaced

s = “abababaabaaba”
s1 = s.replace(“a”, “b”)
print(s1)

Output : bbbbbbbbbbbbbb

String objects are immutable then how we can change the content by using replace() method 

Once we creates string object, we cannot change the content. This non-changeable behavior is nothing but immutability. If we are trying to change the content by using any method, then with those changes a new object will be created and changes won’t be happened in existing object.

Hence the replace() method also a new object got created but existing object won’t be changed.

Eg:

s = “abab”
s1 = s.replace(“a”,”b”)
print(s,”is available at :”,id(s))
print(s1,”is available at:”,id(s1))

Output:

abab is available at : 4568672 
bbbb is available at : 4568704 

In the above example, original object is available and we can see new object which was created because of replace() method.

Splitting of Strings:

We can split the given string according to specified separator by using split() method.

l=s.split(separator)

The default separator is space, the return type of split() method is list.

s=“karth software solutions”
l=s.split()
for x in l:
print(x)

Output:

karth
software
solutions

s=“22-02-2018”
l=s.split(‘-‘)
for x in l:
print(x)

Output 

22
02
2018

Joining of strings:

We can join a group of strings ( list or tuple ) wrt the given separator 

s = (’sunny’,bunny’,’chinny’)
s = ‘-‘.join(t)
print(s)

Output: sunny-bunny-chinny

Eg-2:

l = [‘hyderabad’,’singapore’,’london’,’dubai’]
s = ‘:’.join(l)
print(s)

Output : hyderabad:singapore:london:dubai

Changing case of string:

 We can change case of a string by using the following 4 methods.

upper() —> to convert all characters to upper case 
lower() —> to convert all characters to lower case 
swapcase —> converts all lower case characters to upper case and all upper case characters to Lower case.
title() —>  to convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
capitaize()  —> only first character will be converted to upper case and all remaining characters can be converted to Lower case

s = ‘learning python is very easy’
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

Output:

LEARNING PYTHON IS VERY EASY 
Learning python is very east 
LEARNING pYTHON IS VERY eASY 
Learning Python Is Very Easy
Learning python is very easy 

Checking starting and ending part of the string:

Python contains the following  methods for this purpose:

  1. s.startwith(substring)
  2. s.endswith(substring)

s= ‘learning Python is very easy’
print(s.startswith(‘learning’))
print(s.endswith(‘learning’))
print(s.endswith(‘easy’))

Output 

True
False
True

To check type of characters present in a string 

Python contains the following methods for this purpose.

isalnum(): Returns True if all characters are alphanumeric( a to z, A to Z, 0 to 9)
isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
isdigit(): Returns True if all characters are digits only( 0 to 9)
islower(): Returns True if all characters are lower case alphabet symbols
Isupper(): Returns True if all characters are upper case alphabet symbols
istitle(): Returns True if string is in title case.
isspace(): Returns True if string contains inly spaces 

Eg:

print(‘Karth786’.isalnum()) —> True
print(‘Karth786’.isalpha()) —> False
print(‘Karth’.isalpha()) —> True
print(‘Karth’.isdigit()) —> False
print(‘786786’.isdigit()) —> True
print(‘abc’.islower()) —> True
print(‘Abc’.islower()) —> False
print(‘abc123’.islower()) —> True
print(‘ABC’.isupper()) —> True
print(‘Learning python is Easy’.istitle()) —> False 
print(‘Learning Python is Easy’.istitle()) —> True
print(‘  ‘.isspace()) —> True

Program 

s=input(“Enter any character:”)
if s.isalnum():
print(“Alpha Numeric Character”)
if s.isalpha():
print(“Alphabet character”)
if s.islower():
print(“Lower case alphabet character”)
else:
print(“Upper case alphabet character”)
else:
print(“it is a digit”)
elif s.isspace():
print(“it is space character”)
else:
print(“Non Space Special Character”)

D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character 
It is a digit

D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character 
Alphabet Character 
Lower case alphabet character 

D:\python_classes>py test.py
Enter any character:$
Non Space Special Character 

D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character 
Alphabet Character 
Lower case alphabet character 

Formatting the Strings:

We can format the strings with variable values by using replacement operator {} and format() method 

name = ‘karth’
salary = 10000
age  = 48 
print(“ {} ’s salary is {} and his age is {}”.format(name, salary,age))
print(“{0} ’s salary is {1} and his age is {2}”.format(name, salary,age))
print(“{x} ’s salary is {y} and his age is {z}”.format(z=age,y=salary,x=name))

Output 

karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 

Important Programs regarding String Concept 

Q1 write a program to reverse the given string 

Input: karth
Output: htrak

1st way:
s = input(“Enter Some String:”)
print(s[::-1])

2nd way:
s = input(“Enter Some String:”)
print(“.join(reversed(s)))

3rd way:

s = input(“Enter Some String:”)
i=len(s)-1
target=‘'
while i>=0:
target=target+s[i]
i=i+1
print(target)

Q2 Program to reverse order of words 

Input: Learning Python is vert Easy
Output: Easy Very is Python Learning 

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[I])
i=I-1
output=‘ ‘.join(l1)
print(output)

Output: Enter Some String:Learning Python is very easy!!
             easy!!! Very is Python Learning 

Program to reverse internal content of each word 

Input: Karth Software Solutions
Output: htrak erawtfos snoituloS

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[I][::-1])
i=i+1
output=‘ ‘.join(l1)
print(output)

Write a program to print characters at odd position and even position for the given string ?

1st way:

s =input(“Enter Some String:”)
print(“Characters at Even Position:”,s[0::2])
print(“Characters at Odd Position:”,s[1::2])

2nd way:

s=input(“Enter Some String:”)
i=0
print(“Characters at Even Position:”)
while I<len(s):
print(s[I],end=‘,’)
i=i+2 
print()
print(“Characters at Odd Position:”)
i=1
while I<len(s):
print(s[I],end=‘,’)
i=I+2

Program to Merge Characters of 2 Strings into a Single String by talking Characters alternatively 

Input: s1 = “ravi”
          s2 = “reja”

Output: rtaevjia

s1=input(“Enter First String:”)
s2=input(“Enter Second String:”)
output=‘'
i,j=0,0
while I<len(s1) or j<len(s2)
if i<len(s1):
output=output+s1[I]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

Output:

Enter First String:karth
Enter Second String:ravisoft
kraarvgiasoft

Write a program to sort the characters of the string and first alphabet symbols followed by numeric values 

Input: B4A1D3 
Output: ABD134 

s=input(“Enter Some String:”)
s1=s2=output=‘'
for x in s:
If x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)

Write a program for the following requirement 

Input: a4b3c2 
Output: aaaabbbcc

s=input(“Enter Some String:”)
output=‘'
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)

Note:
chr(unicode) —> The corresponding character 
ord(character) —> The corresponding unicode value

Write a program to perform the following activity 

Input: a4k3b2 
Output: aeknbd

s=input(“Enter Some String”)
output=‘'
for x in s:
If x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x)
print(output)

Write a program to remove duplicate characters from the given input string ?

Input: ABCDABBCDABBBCCCDDEEEF
Ouput: ABCDEF 

s = input(“Enter Some String:”)
l=[]
for x in s:
If x not in l:
l.append(x)
output=“.join(l)
print(output)

Write a program to find the number of occurrences of each character present in the given string ?

s=input(“Enter the Some String:”)
d={}
for x in s:
If x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print(“{} = {} Times”.format(k,v))

Write a program to perform the following task ?

Input: 'one two three four five six seven’
Output: ‘one owt three ruof five xis seven’

s = input(‘Enter Some String:’)
l = s.split()
l1 = []
i = 0
while I<len(l):
if I%2==0:
l1.append(l[I])
else
l1.append(l[I][::-1])
i=I+1
output=‘ ‘.join(l1)
print(‘Original String:’,s)
print(‘output String:’,output)

Output:

D:\python_classes>py test.py 
Enter Some String: one two three four five six seven 
Original String: one two three four five six seven 
output String: one owt three ruof five xis seven

Formatting the strings:

We can format the strings with variable values try using replacement operator {} and format () method 
The main objective of format() method to format string into meaningful output form.

Case 1 : Basic formatting for default, positional and keyword arguments 

name = ‘karth’
salary = 10000
age = 48 
print(“{} ’s salary is {} and his age is {}”.format(name, salary,age))
print(“{0} ’s salary is {1} and his age is {2}”.format(name, salary,age))
print(“{x} ’s salary is {y} and his age is {z}”.format(z=age,y=salary,x=name))

Output

karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 

Case 2: formatting numbers 


d —> Decimal IntEger
f  —> fixed point number ( float ).The default precision is 6
b —> Binary format 
o  —> octal format 
x   —> hexa decimal format ( Lower case )
X   —> hexa decimal format ( Upper case )

Eg: 

print(“The intEger number is: {}”.format(123))
print(“The intEger number is : {:d}”.format(123))
print(“The intEger number is : {:5d}”.format(123))
print(“The intEger number is : {:05d}”.format(123))

Output:

The intEger number is: 123 
The intEger number is: 123 
The intEger number is: 123 
The intEger number is: 00123 

EG:2 

print(“The float number is: {}”.format(123.4567))
print(“The float number is: {:f}”.format(123.4567))
print(“The float number is: {:8.3f}”.format(123.4567))
print(“The float number is: {:8.3f}”.format(123.45))
print(“The float number is: {:8.3f}”.format(786786123.45))

Output:
The float number is: 123.4567
The float number is:  123.456700
The float number is:  123.457
The float number is:   0123.457
The float number is:   0123.450
The float number is:   786786123.450

Note:

{:08.3f}
Total positions should be minimum 8.
After decimal point exactly 3 digits are allowed. If it is less then 0s will be placed in the last positions 
If total number is <8 positions then 0 will be placed in MSBs
If total number is  >8 positions then all integrated; digits will be considered
The extra digits we can take only 0

Note: for numbers default alignment is right alignment (>)

Eg-3: Print decimal value in binary , octal and hexadecimal form 

print(“Binary Form:{0:b}”.format(153))
print(“Octal Form:{0:o}”.format(153))
print(“Hexa decimal Form:{0:x}”.format(154))
print(“Hexa decimal Form:{0:X}”.format(154))

Output 

Binary Form: 10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A

Note :
 we can represent only int values in binary, octal and hexadecimal and it is not possible for float values.
{:5d} it takes intEger argument and assigns a minimum width of 5
{:8.3f} it takes a float argument and assigns a minimum width of 8 including  “.”  And after decimal point exactly 3 digits are allowed with round operation if required.
{:05d} The blank places can be filled with 0. In this place only 0 allowed 

Case3 : Number formatting for signed numbers

> while displaying positive numbers, If we want to include + then we have to write  {:+d} and {:+f}
> using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically.

print(“int value with sign:{:+d}”.format(123))
print(“int value with sign:{:+d}”.format(-123))
print(“int value with sign:{:+f}”.format(123.456))
print(“int value with sign:{:+f}”.format(-123.456))

Output:

int value with sign:+123 
int value with sign:-123 
float value with sign:+123.456000
float value with sign:-123.456000

Case-4 : Number formatting with alignment 

<,>, ^ and = are used for alignment
<  —> left alignment to the remaining space
^  —> center alignment to the remaining space
> —> right alignment to the remaining space
= —> forces the signed (+) (-) to the left most position 

Note: default  alignment for numbers is right alignment.

Eg: 

print(“{:5d}”.format(12))
print(“{:<5d}”.format(12))
print(“{:<05d}”.format(12))
print(“{:>5d}”.format(12))
print(“{:>05d}”.format(12))
print(“{:^5d}”.format(12))
print(“{:=5d}”.format(12))
print(“{:^10.3f}”.format(12.23456))
print(“{:=8.3f}”.format(-12.23456))

Output 

12
12
12000
12
00012
12
-12
12.235
-12.235

Case-5: string formatting with format()
Similar to numbers, we can format string values also with format() method 

s.format(string)

print(“{:5d}”.format(12))
print(“{:5}”.format(“rat”))
print(“{:>5}”.format(“rat”))
print(“{:<5}”.format(“rat”))
print(“{:^5}”.format(“rat”))
print(“{:*^5}”.format(“rat”)) # instead of * we can use any character(like +,$,a etc)

Output 

12
rat
rat
rat
rat
*rat*

Note: for numbers default alignment is right where as for strings default alignment is left 

Case-6 : Truncating strings with format() method 

print(“{:.3}”.format(“karthsoftware”))
print(“{:5.3}”.format(“karthsoftware”))
print(“{:>5.3}”.format(“karthsoftware”))
print(“{:^5.3}”.format(“karthsoftware”))
print(“{:*^5.3}”.format(“karthsoftware”))

Output

kar
kar
kar
kar
*kar*

Case-7 : formatting dictionary members using format()

person={‘age’:48,’name’:’karth’}
print(“{name}’s age is: {age}”.format(**person))

Output: karth’s  age is:48 

Case-8 : formatting class members using format() 

class Person:
age=48
name=“kashu”
print(“{p.name}’s age is :{p.age}”.format(p=Person()))

Output : karth’s age is :48 

class Person:
def_init_(self, name,age):
self.name=name
self.age=age
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘karth’,48)))
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘Ravi’,48)))

Note: Here person object is passed as keyword argument. We can access by using its reference variable in the template string.

 Class-9:  Dynamic formatting using format() 

string=“{:{fill}{align}{width}}”
print{string.format(‘cat’,fill=‘*’,align=‘^’,width=5))
print(string.format(‘cat’,fill=‘*’,align=‘^’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘<’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘>’,width=6))

Output:

*cat*
*cat**
cat***
***cat

Class-10: Dynamic float format template

num=“{:{align}{width}.{precision}f}”
print(num.format(123.236,align=‘<‘,width=8,precision=2))
print(num.format(123.236,align=‘>‘,width=8,precision=2))

Output:

123.24
123.24

Case-11: formatting date values 

import datetime
#datetime formatting 
date=datetime.datetime.now()
print(“it’s now:{:%d/%m/%Y  %H:%M:%S}”.format(date))

Output: it’s now: 09/03/2018 12:36:26

Case-12: Formatting complex numbers 

complexNumbers=1+2j
print(“Real Part:{0.real} and Imaginary Part:{0.imag}”.format(complexNumber))


Output: Real Part: 1.0 and Imaginary Part: 2.0 





Wednesday, December 25, 2019

Flow control statements

Flow control describes the order in which statements will be executed at runtime


                                                                   Control Flow 


Conditional Statements

If
If-elif
If-elif-else 


Transfer Statements 

break
continue
pass


Iterative Statements 

For 
While 

Conditional statements 

  1. If 
If condition: statement 

OR 

If condition 
     statement-1 
     statement-2
     statement-3 

If condition is true then statements will be executed 

Eg:

name=input(“Enter Name:”)
if name==“Karthik” :
print(“Hello Karthik Good Morning”)
print(“How are you!!!”)

D:\Python_classes> py test.py 
Enter Name:karthik
Hello karthik Good Morning 
How are you!!!

D:\Python_classes>py test.py
Enter Name: Karthik
How are you!!!

  1. If-else:

If condition:
     Action-1
else:
     Action-2 

If condition is true then Action-1 will be executed otherwise Action-2 will be executed.

name=input(“Enter Name:”)
if name==“karthik” :
print(“Hello Karthik Good Morning”)
else:
print(“Hello Guest Good Morning”)
print(“How are you!!!”)

D:\python_classes>py test.py
Enter Name:karthik
Hello Karthik Good Morning 
How are you!!!

D:\python_classes>py test.py 
Enter Name:kaush
Hello Guest Good Morning 
How are you!!!

if-elfif-else

if condition1:
       Action-1
elfif condition2:
         Action-2
elfif condition3:
         Action-3
elfif condition4:
         Action-4

else:
      Default Action 

Based condition the corresponding action will be executed.

brand=input(“Enter your favorite choco:”)
if brand==“Cadbury”
print(“It is rich brand”)
elif brand==“kitkat”:
print(“it is not that much sweet”)
elif brand==“ross”
print(“other brands are not recommended”)

D:\python_classes>py test.py
Enter Your  Favorite Brand:choco
It is rich brand

D:\python_classes>py test.py
Enter Your  Favorite Brand:kitkat
it is not that much sweet

D:\python_classes>py test.py
Enter Your  Favorite Brand:ross
other brands are not recommended

Note: 

Else part is always optional. Hence the following are various possible syntaxes 

if
If-else
If-elfif-else
If-elfif

There is no switch statement in python 

Write a program to find biggest of given 2 numbers from the command prompt ?

n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
if n1>n2:
print(“Biggest Number is:”,n1)
else:
print(“Biggest Number is:”,n2)

D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:20
Biggest Number: 20 


Write a program to find biggest of given 3 numbers from the command prompt ?

n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
n3=int(input(“Enter Third Number:”))
if n1>n2 and n1>n3:
print(“Biggest Number is:”,n1)
elif n2>n3
print(“Biggest Number is:”,n2)
else:
print(“Biggest Number is:”,n3)


D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:30
Enter Second Number:20
Biggest Number: 30 

Write a program to check whether the given number is in between 1 and 100 ?

n=int(input(“Enter Number:”))
if n>=1 and n<=10 
print(“The number”,n,”is in between 1 to 10”)
else:
print(“The number”,n,”is not  in between 1 to 10”)

Iterative statements 

If we want to execute a group of statements multiple times then we should go for iterative statements 

Python supports 2 types of iterative statements 

For loop and while loop 

If you want to execute some action for every element present in some sequence ( it may be string or collection ) then we should go for for loop 

Syntax : for x in sequence 
               Body 

Where sequence can be string or any collection 
Body will be executed for every element present in the sequence

Eg: to print characters present in the given string

s=“karthik saru”
for x in s 
print(x)

Output 

K
a
r
T
h
I
K
s
a
r
u

Eg:2 to print characters present in string index wise 

s=input(“Enter some string:”)
I=0
for x in s:
print(“The character present at “,I,”index is :”,x)
i=I+1

D:\Python_classes>py test.py

Enter some string: karthik saru

The character present at 0 index is: k
The character present at 1 index is: a
The character present at 2 index is: r 
The character present at 3 index is: t 
The character present at 4 index is: h 
The character present at 5 index is: i 
The character present at 6 index is: k 
The character present at 7 index is: 
The character present at 8 index is: s
The character present at 9 index is: a
The character present at 10 index is: r
The character present at 11 index is: u

Eg3: To print Hello 10 times 

for x in range(10):
print(“Hello”)

Eg4: To display numbers from 0 to 10 
for x in range(11):
print(x)

Eg5: To display odd numbers from 0 to 20 

for x in range(21)
if(x%2!=0):
print(x)

Eg6: To display numbers from 10 to 1 in descending order 

for x in range(10,0,-1)
print(x)

Eg7: To print sum of numbers present  inside first 

list=eval(input(“Enter List:”))
sum=0;
for x in list:
sum=sum+x;
print(“The Sum=“,sum)

D:\Python_classes>test.py 
Enter List:(10,20,30,40)
The Sum=100

D:\Python_classes>py test.py 
Enter List:[45,67]
The Sum= 112 

  1. While Loop 

If we want to execute a group of statements iteratively until some condition false, then  we should go for while loop 

Syntax: while condition:
             body


Eg: To print numbers from 1 to 10 by using while loop 

x = 1 
while x <=10:
print(x)
x = x+1 

Eg: To display the sum of first n numbers

n=int(input(“Enter number:”))
sum=0
i=1
while i<n:
sum=sum+i
i=i+1
print(“The sum of first”,n,”numbers is:”,sum)

Eg: write a program to prompt user to enter some name until entering karthik 

name=“”
while name!=“karthik”:
name=input(“Enter Name:”)
print(“Thanks for confirmation”)

Infinite loops 

i=0;
while True :
i=I+1;
print(“Hello”,i)

Nested loops:
 
Sometimes we can take a loop inside another loop, which are also knowns as nested loops.

for i in range(4):
 for j in range(4):
print(“I=“,I,”  j=“,j)

I=0 j=0
I=0 j=1
I=0 j=2
I=0 j=3
I=1 j=0
I=1 j=1
I=1 j=2
I=1 j=3
I=2 j=0
I=2 j=1
I=2 j=3
I=2 j=4
I=3 j=0
I=3 j=1
I=3 j=2
I=3 j=3 

Write a program to display  *’s in Right angled triangled form  ?
*
**
***
****
*****
******
*******

n =int(input(“Enter number of rows:”))
for i in range(1,n+1):
for j in range(1,i+1):
print(“*”,end=“”)
print()

Alternative way 

n=int(input(“Enter number of rows:”))
for i in range(1,n+1):
print(“*”*i)

Write a program to display  *’s in pyramid style ( Also known as Equivalent triangle )

                                                    *
                                                   * *
                                                  * * *
                                                  * * * *
                                                  * * * * *
                                                  * * * * * *
                                                  * * * * * * *

n = int(input(“Enter number of rows:”))
for i in range(1,n+1):
print(“ “ * (n-i),end=“”)
print(“* “*I)

Transfer statements 

break:

We can use break statement inside loops to break loop execution based on some condition 

for i in range(10):
if I ==7:
print(“Processing Is enough…plz break”)
break
print(i)

 D:\python_classes>py test.py

0
1
2
3
4
5
6
processing is enough…plz break

Eg:

cart=[10,20,600,60,70]
for item in cart:
If item>500:
print(“To place this order insurance must be required”)
break
print(item)

D:\Python_classes>py test.py
10
20
To place this order insurance must be required

Continue 
 
We can use continue statement to skip current iteration and continue next iteration.

Eg1: To print odd numbers in the range of 0 to 9 

for I in range(10):
if I%2==0:
continue
print(i)

D:\Python_classes>py test.py

1
3
5
7
9

Eg2: 

cart=[10,20,500,700,50,60]
for item in cart:
If item>=500:
print(“We cannot process this item:”,item)
continue
print(item)

D:\Python_classes>py test.py
10
20
We cannot process this item:500
We cannot process this item:700
50
60

Eg3:

numbers=[10,20,0,5,0,30]
for n in numbers 
If n==0:
print(“Hey how we can divide with zero..just skipping”)
continue
print(“100/{} = {}”.format(n, 100/n))

Output 

100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero….just skipping
100/5 = 20.0
Hey how we can divide with zero….just skipping
100/30 = 3.333333

Loops with else block 

Inside loop execution, if break statement not executed, then only else part will be executed
Else means loop with break 

cart=[10,20,30,40,50]
for item in cart:
If item>=500:
print(“We cannot process this order”)
break
print(item)
else:
print(“Congrats…all items processed successfully”)

Output

10
20
30
40
50
Congrats…all items processed successfully

Eg: 

cart=[10,20,600,30,40,50]
for item in cart:
If item>=500
print(“We cannot process this order”)
break 
print(item)
else:
print(“Congrats…all items processed successfully”)

Output 

D:\Python_classes>py test.py 
10
20
We cannot process this order 

What is the difference between for loop and while loop in python ?

We can use loops to repeat code execution 
Repeat code for every item in sequence  —> for loop 
Repeat code as long as condition is true —> while loop 

How to exit from the loop ? By using break statement 
How to skip some iterations inside loop ? By using continue statement 
When else part will be executed wrt loops ? If loop executed without break 

Pass statement 

Pass is a keyword in python 
In our programming syntactically if block is required which won’t do anything then we can define that empty block will pass keyword.

pass
  •     It Is an empty statement 
  • It is null statement 
  • It won’t do anything 

Eg: if True
SyntaxError: unexpected EOF while parsing 
If True: pass —> valid 

def m1():

SyntaxError: unexpected EOF while parsing 
def m1(): pass 

Use case of pass 

Sometimes in the parent class we have to declare a function with empty    body and child class responsible to provide proper implementation. Such type of empty body we can define by using pass keyword. ( it is something like abstract method in java).

for I in range(100)
if I%9==0
print(i)
else:pass 

D:\Python_classes>py test.py
0
9
18
27
36
45
54
63
72
81
90
99

del statement:

del is a keyword in python 
After using a variable, it is highly recommended to delete that variable if it is no longer required, so that the corresponding object is eligible for garbage collection.

We can delete variable by using del keyword.

x = 10
print(x)
del x 

After deleting a variable we cannot access that variable otherwise we will get NameError

x = 10
del x 
print(x)

NameError: name ‘x’ is not defined 

Note: we can delete variables which are pointing to immutable objects. But we cannot delete the elements present inside immutable object.

s = “karthik”
print(s)
del s —> valid 
del s[0] —> TypeError: ’str’ object does not support item deletion

Difference b/w del and None 

In the case del, the variable will be removed and we cannot accsss that variable(unbind operation)

s = “karthik”
del s 
print(s) —> NameError: name ’s’ is not defined.

But in the case of None assignment the variable won’t be removed but the corresponding object is eligible for garbage collection ( re bind operation), Hence after assigning with none value, we can access that variable.

s = “karthik”
s = None
print(s) —> None