python-notes-class-xi-cs-083_removed (1) (1)
python-notes-class-xi-cs-083_removed (1) (1)
STRING IN PYTHON
6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, …….. in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
The index of string in forward direction starts from 0 and in backward direction starts
from -1.
The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)
https://pythonschoolkvs.wordpress.com/ Page 50
Output:
kendriya
i. String concatenation Operator: The + operator creates a new string by joining the two
operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
https://pythonschoolkvs.wordpress.com/ Page 51
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
https://pythonschoolkvs.wordpress.com/ Page 52
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
Example:
>>> ord('b')
98
>>> chr(65)
'A'
https://pythonschoolkvs.wordpress.com/ Page 53
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
https://pythonschoolkvs.wordpress.com/ Page 54
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
https://pythonschoolkvs.wordpress.com/ Page 55
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
https://pythonschoolkvs.wordpress.com/ Page 56
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first character >>> str.capitalize()
capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the string where the >>> str.find("ruct",5,13)
substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> str.find("ruct",8,13)
-1
4 isalnum( ) Returns True if the characters in the string are >>>s1.isalnum( )
alphabets or numbers. False otherwise True
>>>s2.isalnum( )
True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the string are >>>s1.isalpha( )
alphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in the string are >>>s1.isdigit( )
digits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in the string are >>> s1.islower()
lowercase. False otherwise. True
>>> s2.islower()
https://pythonschoolkvs.wordpress.com/ Page 57
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
8 isupper( ) Returns True if all the characters in the string are >>> s1.isupper()
uppercase. False otherwise. False
>>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace >>> " ".isspace()
characters in the string. False otherwise. True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it removes the ' structure'
leading whitespaces. >>> str.lstrip('data')
' structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the trailing >>> str.rstrip('eur')
characters. (Right side). 'data struct'
if used without any argument, it removes the >>> str.rstrip('rut')
trailing whitespaces. 'data structure'
>>> str.rstrip('tucers')
'data '
14 split( ) breaks a string into words and creates a list out of it >>> str="Data Structure"
>>> str.split( )
['Data', 'Structure']
https://pythonschoolkvs.wordpress.com/ Page 58
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the first
letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)
2. Write a program that reads a string and checks whether it is a palindrome string or
not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
https://pythonschoolkvs.wordpress.com/ Page 59
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")
3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")
https://pythonschoolkvs.wordpress.com/ Page 60
CHAPTER-7
LIST IN PYTHON
7.1 Introduction:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax:
Example:
https://pythonschoolkvs.wordpress.com/ Page 61
mylist = list(("apple", "banana", "cherry")) #note the double round-brackets
print(mylist)
>>> L
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> L1
https://pythonschoolkvs.wordpress.com/ Page 62
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.
>>> L1
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes.
List-name[start:end] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
https://pythonschoolkvs.wordpress.com/ Page 63
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Method-1:
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
https://pythonschoolkvs.wordpress.com/ Page 64
Joining Operator: It joins two or more lists.
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
>>> number[4:20]
>>> number[-1:-6]
[]
>>> number[-6:-1]
https://pythonschoolkvs.wordpress.com/ Page 65
>>> number[0:len(number)]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
>>> number[2:4]=["computer"]
>>> number
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
https://pythonschoolkvs.wordpress.com/ Page 66
Comparison Operators:
Example:
https://pythonschoolkvs.wordpress.com/ Page 67
List Methods:
Consider a list:
company=["IBM","HCL","Wipro"]
S. Function
No.
Description Example
Name
1 append( ) To add element to the list >>> company.append("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
list-name.append (element)
Error:
>>>company.append("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)
4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> company.index("Wipro")
Syntax: 2
list-name.index(element)
Error:
>>> company.index("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
https://pythonschoolkvs.wordpress.com/ Page 68
>>> company.index(2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> company.insert(2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
list.insert(index, element)
>>> company.insert(16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
>>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
https://pythonschoolkvs.wordpress.com/ Page 69
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> company.pop(1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
list-name.pop(index)
>>> company.pop( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
Error:
>>>L=[ ]
>>>L.pop( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=company.copy( )
Syntax: >>> L
list-name.copy( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> company.reverse()
Syntax: >>> company
list-name.reverse( ) ['Wipro', 'HCL', 'IBM']
Takes no argument,
returns no list.
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>company.sort( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
list-name.sort( )
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
https://pythonschoolkvs.wordpress.com/ Page 70
Deleting the elements from the list using del statement:
Syntax:
Example:
>>> L=[10,20,30,40,50]
>>> L
>>> L= [10,20,30,40,50]
>>> L
>>> del L # deletes all elements and the list object too.
>>> L
https://pythonschoolkvs.wordpress.com/ Page 71
Difference between del, remove( ), pop( ), clear( ):
S.
del remove( ) pop( ) clear( )
No.
S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list as Takes two arguments,
2 Takes one element as argument
argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.
https://pythonschoolkvs.wordpress.com/ Page 72
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
https://pythonschoolkvs.wordpress.com/ Page 73
Program-2 Find the second largest number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
seond=max
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
https://pythonschoolkvs.wordpress.com/ Page 74