Python Revision-Part 2
Strings in Python
Strings in Python
Strings are stored as individual characters in contiguous locations, with two-way index for each location.
Each character in a string can be accessed using its index number.
Example: x=“PYTHON”
0 1 2 3 4 5 Forward indexing x[0]=P=x[-6]
PYTHON x[1]=Y=x[-5]
-6 -5 -4 -3 -2 -1 Backward Indexing x[2]=T=x[-4]
x[3]=H=x[-3]
Length of the string can be determined by using len() function.
len(x) gives 6 as output.
Traversing a string means iterating the elements of a string using loops.
Example: x=“PYTHON”
for i in x:
print(i,end=“ “) Output is P Y T H O N
String Operators
+ (Concatenation Operator): Both operands should be same type.
Example: “Power”+”Ful” gives “PowerFul”, ‘20’+’10’ gives ‘2010’
*(Replication Operator) : one operand is a string and other operand should be a number. It
returns the repetition of a particular string to the corresponding number of times.
Example: ”Hai”*3 returns ‘HaiHaiHai’
Membership Operator(in & not in ): checks whether a particular character or substring is
present in the given string or not.
Example: ‘a’ in ‘hai’ returns True
‘a’ not in ‘apple’ returns False.
Comparison Operators(<, >,<=,>=,==,!=)
String Slicing: Slicing means a part of the string.
Syntax: string[start:stop:step]
X=“PYTHON” a=“Hello World”
print(x[1:5]) returns Y T H O print(a[:5]) returns Hello
print(a[::-1]) returns dlroW olleH
String Functions
string.capitalize() : returns a string with its 1st letter capitalized.
string.isalpha(): Returns True if the string contains only alphabets.
string.isdigit(): Returns True if the string contains only digits.
string.isalnum(): Returns True if the string contains alphabets and numbers.
string.isspace(): Returns True if there is only white space characters in the string.
Ex: >>>string=“ “ string.isspace() returns True
>>>string1=“” string.isspace() returns False
string.islower(): Returns True if all characters in the string are lowercase.
string.isupper():Returns True if all characters in the string are uppercase.
string.lower(): converts the string into lowercase.
string.upper(): converts string into uppercase.
string.lstrip():It removes the leading whitespaces in the string.
string.rstrip(): It removes the trailing whitespaces in the string.
find(): It is used to search the first occurrence of the substring in the given string.
*The find() method returns the lowest index of the substring if it is found in the given
string.
* If the substring is not found, it returns -1.
Syntax: str.find(sub, start, end)
sub : substring to be searched
start: starting position from where substring is to be checked
end: end position is the index of the last value for specified range.
Example: word=‘Green Revolution’
Result= word. find(‘Green’)
print(Result) # Output is 0.
Result1=word. find(‘green’)
print(Result1) # Output is -1
Str1= “Swachh Bharat Swasth Bharat”
Str1.find(“Bharat”,13,28) #Output is 21
split(): this method breaks up a string at the specified separator and returns a list of
substrings.
Syntax: str.split(separator, maxsplit)
separator: Optional parameter. The separator is a delimiter. The string separates at a
specified separator. If the seperator is not specified, by default whitespace( space, newline,
etc) string is a separator.
maxsplit: Optional parameter. It defines the maximum number of splits. Default value
is -1 which means no limit on the number of splits.
Example:
x=‘CS; IP; IT’
x.split(“ ; ”) Output is [‘CS’, ‘IP’, ‘IT’]
x.split(‘ ; ’, 2) Output is [‘CS’, ‘IP’, ‘IT’]
x.split(‘ ; ‘, 1) Output is [‘CS’, ‘IP; IT’]
X=‘Good Morning’
x.split() Output is [‘Good’, ‘Morning’]
Lists in Python
It is a collection or ordered sequence of comma separated values of any type such as integers,
strings, float, or even a list or tuples.
Elements in the list are enclosed in square brackets [] .
Elements can be accessed by using its index value. It is a mutable data type.
Ex: fruits=[‘Mango’, ‘Banana’, ‘Apple’]
fruits[0]=Mango
Creating list using list():
Example l=list(‘hello’)
print(l) gives [‘h’,’e’,’l’,’l’,’o’]
Creating list using eval():
We use eval() to input list from user.
Example: l1=eval(input(“Enter List Elements:”)) Output
print(l1) Enter List Elements: [10,20,30,40]
[10,20,30,40]
List Operations
Traversing: Accessing each element in a list using for loop.
Example: l=[‘P’,’Y’,’T’,’H’,’O’,’N’]
for i in l:
print(i)
Joining Lists: ‘+’ operator is used to join 2 lists.
Example: l1=[1,2,3] l2=[4,5,6] l1+l2=[1,2,3,4,5,6]
Replicating Lists:’*’ operator is used to repeat a list for particular number of times.
Example: l1*3 returns [1,2,3,1,2,3,1,2,3]
Slicing a list: Slicing means the subpart of a list.
syntax: l[start:stop:step]
Example: l1=[10,12,14,16,18,20]
l1[2:5] is [14,16,18]
l1[0:2]=100
print(l1) gives [100,14,16,18,20]
List Functions
index(): Returns the index of first matched item from the list. Syntax: list.index(item)
Example: L=[13,18,11,16,18,14]
print(L.index(18)) gives 1
append():Adds an item to the end of the list. Syntax: list.append(item)
Example: L=[‘Red’,’Black’,’Green’]
print(L.append(‘Yellow’)) gives [‘Red’, ‘Black’, ‘Green’ ,’Yellow’]
extend(): Used for adding multiple elements to a list. Syntax: list.extend(list1)
Example: l1=[‘a’,’b’,’c’], l2=[‘d’,’e’]
print(l1.extend(l2)) gives [‘a’,’b’,’c’,’d’,’e’]
insert(): inserts an element t a given position. Syntx: list.insert(pos, item)
Example: l1=[‘a’, ’e’, ’i’]
print(l1.insert(2,’u’)) gives [‘a’, ‘e’, ‘u’, ‘I’]
pop(): removes an element from a given position in the list and return it.
Syntax: list.pop(index)
Example: l=[‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’]
print( l.pop(0)) gives C
remove(): removes the first occurrence of the given element in the list.
Syntax: list.remove(item) If del keyword is used, it
Example: l1=[‘A’, ‘B’, ‘C’, ‘A’, ‘P’, Q’] will delete the list
elements as well as the
l1.remove(‘A’) list.
print(l1) gives [‘B’, ‘C’, ‘A’, ‘P’, ‘Q’]
clear(): removes all items from the list and list becomes empty. Syntax: list.clear()
Example: l=[5,6,7]
l.clear()
print(l) gives []
count(): Returns te number of times an element is present in the list. Syntax: list.count(item)
Example: l=[13,18,20,10,18,23]
print( l.count(18)) gives 2
reverse():reverses the elements in the list. Syntax: list.reverse()
Example: l=[‘a’, ‘b’ ,’c’, ‘d’, ‘e’] print(l.reverse()) gives [‘e’, ‘d’, ‘c’, ‘b’, ‘a’]
sort(): Sorts the items in the list. Syntax: list.sort()
Example: l=[25,10,15,0,20] print( l.sort()) gives [0,10,15,20,25]
Activity
Write a Python program to perform linear search on a user inputted list.
Write a python program to check whether the given string is palindrome or
not.