Professional Documents
Culture Documents
1. Strings:
❖ String is a sequence which is made up of one or more UNICODE
characters.
❖ The character can be a letter,digit, whitespace or any other symbol.
❖ Python has a built-in string class named "str" that has many useful
features.
❖ A string can be created by enclosing one or more characters in
single,double or triple quote.
❖ To declare and define a string by creating a variable of string type:
>>> name = "India"
>>> graduate = 'N’
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
>>>country = name nationality = str("Indian")
`
>>> str = "Hello World!"
>>> str[3]
>>> l
❖ The index of the first character is 0 and that of the last character is n-1
where n is the length of the string.
❖ The index must be an integer (positive, zero or negative).
❖ Negative indices are used when the characters of the string are accessed
from right to left.
❖ Starting from right hand side, the first character has the index as -1 and
the last character has the index –n where n is the length of the string.
>>> str[-3]
>>> r
❖ The index can also be an expression including variables and operators but
the expression must evaluate to an integer.
3. String slices:
➢ A substring of a string is called a slice. The slice operation is used to
refer to sub-parts of sequences and strings within the objects.
➢ Slicing operator [ ] is used to access subset of string from original string
➢ Syntax :
string_var [START INDEX : END INDEX: STEP]
`
>>>'HloWr'
>>> str1[0:10:3]
>>>'HlWl'
Note :
1. The numbers of characters in the substring will always be equal to
m-n
>>> str1= "Hello World!"
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
>>> 'lo World!'
2. If the first index is not mentioned, the slice starts from index 0.
>>> str1[:5]
>>> 'Hello'
3. If the second index is not mentioned, the slicing is done till the
length of the string.
>>> str1[6:]
>>>'World!'
4. Negative indexes can also be used for slicing.
>>> str1[-6:-1]
>>> 'World'
4. Traversing a String:
To access each character of a string or traverse a string, for loop and while
loop are used
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
>>> Hello World! #output of for loop
➢ for loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.
`
5. Immutability:
➢ A string is an immutable data type.
➢ The contents of the string cannot be changed in-place after it
has been created. An attempt to do this would lead to an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment
iii. Membership : Python has two membership operators 'in' and 'not
in'. The 'in' operator takes two strings and returns True if the first
string appears as a substring in the second string, otherwise it
returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
>>> True
>>> 'My' in str1
>>> False
The 'not in' operator also takes two strings and returns True if the
first string does not appear as a substring in the second string,
otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
>>> True
>>> 'Hello' not in str1
>>> False
`
iv. Comparing strings: Two strings can be compared using relational
operators which return True or False
`
7. String Methods:
5. str.title ( ) : Return a title cased version of the string, where words start
with an uppercase character and the remaining characters are lowercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! !
`
>>> str=" this2009 ”
>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False
10. str . isspace ( ) : Return True, if there are only whitespace characters in
the string, otherwise False is returned.
>>> str= " "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False
11. str.islower ( ) : Return True, if all cased characters in the string are in
lowercase, false otherwise.
>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True
12. str.isupper ( ) : Return True, if all cased characters in the string are
uppercase, otherwise False isreturned.
`
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.isupper ( )
True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )
False
15. str.index ( sub [ , start [ , end ] ] ) : Return the lowest index in the string
where the sub-string sub is found, such that sub is contained in the slice s
[ start: end] (like find ( ) but raise ValueError when the sub-string is not
found)
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 )
15
>>> str1.index ( str2 , 10 )
15
`
>>> str1=" this is really a string example. . . .wow !
! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
17. str. join ( iterable ) : Return a string which is the concatenation of the
strings in the iterable. The separator between elements is the string str
providing this method.
>>> str="-"
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq)
' a-b-c '
18. str.replace ( old , new [ , count ] ) : Return a string with all occurrences
of substring old replaced by new. If the optional argument count is given,
only the first count occurrences are replaced.
>>> str=" this is string example. . . . wow ! ! ! this
is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was
really string’
`
>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! !
! '
22. str.strip ( [ chars ] ) : Return a string with the leading and trailing
characters removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None, the chars argument defaults
to removing whitespace.
>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '
23. str.split ( [ sep [ , maxsplit ] ] ) : Return a list of the words from the
string using sep as the delimiter string. If maxsplit is given, at most
maxsplit splits are done (thus, the list will have at most maxsplit + 1
elements). If maxsplit is not specified or -1, then all possible splits are
made. If sep is not specified or None, any whitespace string is a separator.
>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]
24. str. splitlines ( [ keepends ] ) : Return a list of the lines in the string,
breaking at line boundaries. Line breaks are not included in the resulting
list unless keeping is given.
>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "
>>> str.splitlines ( )
[ ' Line1-a b c d e f', ' Line2- a b c ' , ' ' , ' Line4- a b
c d ' ]
9. Lists : List are ordered collections of other objects which are mutable.
It is a sequence in which elements are written as a list of comma-separated
values (items) between square brackets.
The key feature of a list is that it can have elements that belong to different
data types.
Syntax for defining a list
List_variable = [val1, val2,...]
Ex.
`
11. Access Values in Lists
List Index : Index operator [ ] to access an item in a list.
Indices start at 0
Ex:
l=[10,20,30,40,50,60,70]
print(l[5])
Output:
60
Slicing List : To access values in lists, square brackets are used to slice
along with the index or indices to get value stored at that index.
Output:
[40, 50, 60, 70]
Output:
e
p
`
13. Mutability :
The list is a data type that is mutable. Once a list has been created:
➢ Elements can be modified.
➢ Individual values can be replaced.
➢ The order of elements can be changed.
Lists are also dynamic. Elements can be added and deleted from a list,
allowing it to grow or shrink
Ex:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham',
'lobster']
>>> a[2] = 10
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 'lobster']
>>> a[-1] = 20
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 20]
15. List traversal: To iterate over all the elements in a list the
following methods can be used.
Method #1: Using For loop
list = [1, 3, 5, 7, 9] Output :
for i in list: 1
print(i) 3
5
7
9
`
print("3 in x :", x + y)
print(x>y, x!=y)
print(len(x))
print("Maximum in list x :", max(x))
print("Minimum in list x :", min(x))
print("Sum of list x :", sum(x))
print("all fn using y :", all(y))
print("any fn using y :", any(y))
print("sorting list x :", sorted(x))
print("Converting string to list :", list("abcd"))
Output :
Concatenation of list x and y : [5, 2, 3, 7, 9, 10]
Repetition of list y : [7, 9, 10, 7, 9, 10, 7, 9, 10]
3 in x : [5, 2, 3, 7, 9, 10]
False True
3
Maximum in list x : 5
Minimum in list x : 2
Sum of list x : 10
all fn using y : True
any fn using y : True
sorting list x : [2, 3, 5]
Converting string to list : ['a', 'b', 'c', 'd']
`
n=[6,0,1,2,9]
n.append(10)
print(n)
n.append([11,12,13])
print(n)
Output :
[6, 0, 1, 2, 9, 10]
[6, 0, 1, 2, 9, 10, [11, 12, 13]]
3. index ( ) : Returns the lowest index of obj in the list. Gives a Value
Error if obj is not present in the list.
Syntax : list.index(obj)
n=[6,0,1,2,9,3,2,0,3]
print(n.index(9))
print(n.index(10))
Output :
4
Traceback (most recent call last):
File "<string>", line 3, in <module>
ValueError: 10 is not in list
`
n=[6,0,1,2,9]
n.insert(2,50)
print(n)
Output :
[6, 0, 50, 1, 2, 9]
`
print(n)
n.remove(10)
print(n)
Output :
[6, 0, 2, 9]
Traceback (most recent call last):
File "<string>", line 4, in <module>
ValueError: list.remove(x): x not in list
`
n=[6,0,1,2,9]
n.clear()
print(n)
Output :
[ ]
11. copy ( ) : Returns a copy of the list
Syntax : list.copy ( )
n=[6,0,1,2,9]
a=n.copy()
print(n)
print(a)
Output :
[6, 0, 1, 2, 9]
[6, 0, 1, 2, 9]
Output:
139985896812096
139985896812096
`
➢ If changes are done in reference variable content, then those changes
will be reflected to the other reference variable.
Ex:
x=[10,20,30,40]
y=x
y[1]=777
print(x)
Output :
[10,777,30,40]
Output :
[10,20,30,40]
[10,777,30,40]
`
(ii) Using the list() method- cloning a list by using the built-in
function list( )
Ex:
def Cloning(li1):
li_copy = list(li1)
return li_copy
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
(iii) Using the copy() method - The inbuilt method copy is used to
copy all the elements from one list to another
Ex:
def Cloning(li1):
li_copy =[]
li_copy = li1.copy()
return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
`
(iv) Using the append() / extend() method - This can be used for
appending and adding elements to list or copying them to a new
list. It is used to add elements to the last position of list.
Ex:
def Cloning(li1):
li_copy =[]
for item in li1:
li_copy.append(item)
return li_copy
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
`
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Example 2: To find even number list in a range of integers
>>> [i for i in range(10) if i % 2 ==0]
>>>[0, 2, 4, 6, 8]
Output:
Enter a string: Radar
Radar is a palindrome
`
Output:
Enter no. of
elements:5enter
value:23
enter
value:45
enter
value:67
enter
value:89
enter
value:100
[23,45,67,89,
100]
enter value to be
searched:67Element found
at index 2
A=[[1,2,3],
[1,2,3],
[1,2,3]]
B=[[2,3,1],
[2,3,1],
[2,3,1]]
C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j]+=A[i][k]*B[k][j]
for r in C:
print(r)
Output :
[12, 18, 6]
[12, 18, 6]
[12, 18, 6]
A=[[3,3,3],
[2,2,2],
[1,1,1]]
B=[[1,1,1],
[2,2,2],
[3,3,3]]
C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
C[i][j]=A[i][j]+B[i][j]
for r in C:
print(r)
Output :
[4, 4, 4]
[4, 4, 4]
[4, 4, 4]
`
#iii) TRANSPOSE OF MATRIX
A=[[1,2,3],
[4,5,6]]
B=[[0,0],
[0,0],
[0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
B[j][i] = A[i][j]
for r in B:
print(r)
Output :
[1, 4]
[2, 5]
[3, 6]
Program:
list1=[2,8,4,5]
list2=[4,7,8,9]
list_intersection = list(set(list1) ^ set(list2))
print("Intersection of {} and {} is : {}".format(
list1, list2, list_intersection))
Output:
Intersection of [2, 8, 4, 5] and [4, 7, 8, 9] is : [2, 5, 7, 9]
6. Write a function called is_anagram that takes two strings and returns True if they are anagrams.
Program:
def is_anagram(s1,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return True
else:
return False
Output:
enter 1st string:Ajax
enter 2nd string:Jaxa
`
Is Anagram: True
7. Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the character
from the string and return the new string.
Program:
def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))
Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz
8. Write a Python program to count Uppercase, Lowercase, special character and numeric
values in a given string.
Programs:
v='Shop open@3pm'
s=v.replace(" ","")
a=0
b=0
c=0
d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)
Output:
digit values: 1
`
uppercase letters: 1
lower case letters: 9
special charc: 1
str1="".join(str.split())
vowel="aeiou"
vcount=0
ccount=0
for i in str1:
if i.lower() in vowel:
vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount)
print("No. of consonents in string ",str ,ccount)
Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string python program 10