0% found this document useful (0 votes)
37 views8 pages

Python Rivision Tour-2

Uploaded by

arunkesarwani819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views8 pages

Python Rivision Tour-2

Uploaded by

arunkesarwani819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CHapte-@ Athon hevisien Touj-2

STRINGS
A sequence of characters is called a string.
manipulate text such as words and sentences.Strings are used byprogramming languages to
Strings literal in Python are enclosed by
span multiple lines, to write these stringsdouble quotes or single quotes. String literals can
>>>a= "Python triple quotes are used.
Empty string can also be created in
Programming
Language'** Python.
>>>str =*
Accessing Values in Strings
Each individual character in a string can be assessed
Python allows both positive and negative indexing. using a technique called indexing.
S="Python Language"
3 4 6 7 10 12 13
P h L a n a
-15 -14 -13 -12 -|| -10 -9 -8 -7 -6 -5 -4 -3 -2
>>> S[7)
>>>S[-10)
Deleting a String n

Aswe know, strings are immutable, so we


string but we can delete entire string using cannot delete or remove the characters from the
del keyword. >>> strl ="
>>> del strl
WELCOME"
String Slicing >>> print ( strl )
To access some part of a string or NameError :name 'strl'is not defined.
Syntax: string name[start :stop] substring, we use a method called slicing.
>>> strl ="Python Program "
>>> print (strl[3: 8]) >>> print (strl [: -4])
hon P
Python Pro
>>> print (strl [5:])
Strings are also provide slice steps which used to n Program
extract
consecutive. Syntax string name start : stop: step ] characters from string that are not
>>> print ( stri [ 2:12:3])
tnrr
We can also print all characters of
>>> print ( strl [:: -1]) string in reverse order using [ :-1]
margorP nohtyP
Traversing a String
1. Using'for' loop: for loop can
iterate over the elements of asequence or
when you want to traverse all characters ofa string. eg. string. It is used
>>> sub =" GOODD "
>>> fori in subs: Output:
print (i)
2. Using 'for' loop with range D
>>> sub = " COMPUTER "
>>> for iin range ( len( sub ) ):
print (sub [ i], -',end = )
Output: Output C-0-M - P-U-T-E -R
String Operations
Concatenation
Toconcatenate means to join.
Python allows us to join two strings using the
operator plus which is denoted by symbol +. concatenation
>>> strl = 'Hello' #First string
>>> str2 =World!" #Second string
>>> strl + str2#Concatenated strings 'HelloWorld!'
String Replication Operator (*)
Python allows us to repeat the given string using repetition operator which is denoted by
symbol ().
>>>a = 2* " Hcllo "
>>> print ( a )
HelloHello
Comparison Operators
Python string comparison can be performed using comparison operators (==,>
-).These operators are as follows
>>> a ='python'< program
>>> print (a)
False
>>> a='Python "
>>> b='PYTHON "
>>>a >b
True
Membership Operators are used to find out whether a value is a member ofa string or not.
(i) in Operator: (ii) not in Operator:
>>>a="Python Programming Language" >>>a= "Python Programming Language"
>>> "Programming" in a >>> "Java" not in a
True True
BUILT IN STRING METHODS
Method Description
len() Returns length ofthe given string
title() Returns the string with first letter of every word in the string in
uppercase and rest in lowercase
lower() Returns the string with all uppercase letters converted to
lowercase
Returns the string with all lowercase letters converted to
upper)
uppercase
count(str, start, end) Returns number of times substring str occurs in the given string.
find(str,start, Returns the first occurrence of index of substring stroccurring in
end) the given string. If the substring is not present in the given string,
then the function returns -1
index(str, start, end) Same as find() but raises an exception if the substring is not
present in the given string
endswith() Returns True if the given string ends with the supplied substring
otherwise returns False
startswith) Returns True if the given string starts with the supplied substring
otherwise returns False
isalnum() Returns True if characters of the given string are either alphabets
or numeric: If whitespace or special symbols are part of the given
string or the string is empty it returns False
islower() Returns True if the string is non-empty and has all lowercase
alphabets, or has at least one character as lowercase alphabet and
rest are non-alphabet characters
Page9
has all uppercase
isupper() Returns True if the string is non-empty and uppercase character and
alphabets, or has at least one character as
rest are non-alphabet characters
and all characters are
isspace() Returns Tue if the string is non-empty
return)
white spaces (blank, tab, newline, carriage title case, i.e., the first
non-empty and
istitle() Returns True ifthe string is
and rest in
letter of every word in the string in uppercase
lowercase
only on the left of the
Istrip() Returns the string after removing the spaces
string right of
rstrip() Returns the string after removing the spaces only on the
the string
both on the left and
strip() Returns the string after removing the spaces
the right of the string new string
replace (oldstr, newstr) Replaces all occurrences of old string with the
the string have been
join() Returns a string in which the characters in
joined by a separator
the substring
partition () Partitions the given string at the first occurrence of
parts.
(separator) and returns the string partitioned into three
1. Substring before the separator
2. Separator
separator is not found in the
3. Substring after the separator Ifthe strings
string, it returns the whole string itselfand two emptysubstring. Ifno
Returns a list of words delimited by the specified
split()
delimiter is given then words are separated by space.

LIST
data at the same time. List
List is an ordered sequence, which is used to store multiple
contains a sequence of heterogeneous elements. Each elementindex of alist is assigned a number
is 1 ,the third index is 2
to its position or index. The first index is 0 (zero), the second
and so on.
Creating a List In Python,
a=[34,76, 11,98]
b=['s',3,6,'t']
d=(0
Creating List From an Existing Sequence: list () method is used to create list from an
existing sequence. Syntax: new_list _name =list ( sequence / string )
You can also create an empty list . eg. a = list().
Similarity between List and String
len ( ) function is used to return the number of items in both list and string.
Membership operators as in and not in are same in list as well as string.
Concatenation and replication operations are also same done in list and string.
Diference between String and List
Strings are immutable which means the values provided to them will not change in the
program. Lists are mutable which means the values of list can be changed at any time.
Accessing Lists
To access the list's elements, index number is used.
S=[12,4,66,7,8,97, "computer",5.5,] 0 2 3 4 5 6 7
>>> S[5]
10
Page 97 12 4 66 7 8 97 computer 5.5
>>>S[-2] -8 -7 -6 -5 -4 -3 -2
computer
Traversing a List
Traversing a list is a technique to access an individual element of that list.
1. Using for loop for loop is used when you want to traverse each element of alist.
>>>a=[p','r,'o.'g'.'r','a','m']
>>> fot x in a:
print(x, end = ) output : program
2. Using for loop with range( )
>>>a=['p.r',;o'.'g'.'r,'a','m']
>>> fot x in range(len(a)):
print(x, end = ) output : progra m
List Operations
1. Concatenate Lists
List concatenation is the technique of combining two lists. The use of +operator can easily
add the whole of one list to other list.Syntax list listl+list2 e.g. >>>Ll=[43, 56.34 ]
>>> L2 =|22, 34, 98 ]
2. Replicating List >>>L= || + 12
Elements of the list can be replicated using * operator >>>L[43, 56. 34, 22, 34,98 ]
Syntax list =list| * digit e.g. >>> LI=[3.2,6]
>>>L= 1|2
>>>L [3.2.6,3,2,6]
3. Slicing of a List: List slicing refers to access a specific portion or a subset of the list for
some operation while the original list remains unaffected
Syntax:- list_name [ start: end ] Syntax: list_name [ start: stop : step ]
>>> Listl =[4,3,7,6,4,9,5,0,3, 2] >>> Listl =[4.3.,7.6.4.9.5,0.3, 2]
>>> S=Listl[ 2:5 ] >>>S=istl[ 1 :9:3]
>>>S >>>

[7, 6,4) [3.4,0]


List Manipulation
Updating Elements in a List
List can be modified after it created using slicing e.g.
>>> ||=[2,4, " Try", 54, " Again "]
>>> 1[ 0:2]=[34, " Hello "]
>>>||
[34, ' Hello', Try. 54,' Again ]
>>> ||[4]=[ "World "]
>>>||
[34, ' Hello "Try', 54, ('World )
Deleting Elements from a List
del keyword is used to delete the clements from the list.
Syntax:
del list_ name [ index ] #to delete individual element
del lIst_ name [ start : stop ] #to delete elements in list slice c.g.
>>> list|=(2.5,4.7,7,7.8.90]
>>> del list| [3] >>> del listl[2:4]
>>> list l >>> list!
(2.5. 4. 7. 7, 8, 90] [2.5,4. 8. 90]
BUILT IN LIST METHODS
Method Description
11
Page len() Returns the length of the list passed as the argument
list() Creates an empty list if no argument is passed
Creates a list if asequence is passed as an argument
append) of the list
Appends asingle element passed as an argument at the end end of the given list
extend) Appends cach element ofthe list passed as argument to the
insert() Inserts an clement at aparticular index in the list the list
count() Retuns the number of times a given clement appearsthein list. Ifthe element is
the clement in
index() neurns Index ofthe first occurrence of
not present, ValueError is generated element is present multiple
remove() Kemoves the given element from the list. If the element is not present, then
imes, only the first occurrence is removed. If the
ValuclError is generated and
passed as parameter to this function
pop() Keurns the element whose index is paramcter is given, then it returns and
also removes it from the list. If no
removes the last clement of the list
reverse) Reverses the order of clements in the given list
sort() Sorts the elements of the given list in-place consisting ofthe same elements
creates a new list
sorted() Ittakes a list as parameter and
arranged in sorted order
list
min) Returns minimum or smallest element of the
the list
max() Returns maximum or largest element of
sum() Returns sum of the elements of the list

TUPLES
sequence of
is an ordered sequence of elements of different data types. Tuple holds a
A tuple elements and do not allow changes
heterogencous elements, it store a fixed set of
Tuple vs List elements of alist are mutable.
Elements of a tuple are immutable whereas
Tuples are declared in parentheses () while lists are declared in square brackets (].
aster compared to iterating over a list.
Iterating over the elements of atuple is
Creating a Tuple
in parentheses ( ). separated by commas.
To create a tuple in Python, the elements are kept
a=(34,76. 12,90 )
b=('s',3,6,'a')
of tuples, Replication oftuples
Accessing tuple elements, Traversing a tuple, Concatenation
and slicing of tuples works same as that of List
BUILT IN TUPLE METHODS
Method Description
Argument
len() Returns the length or the number ofelements of the tuple passed as
sequence is
tuple() Creates an empty tuple if no argument is passed. Creates a tuple if a
passed as argument
count() Returns the number of times the given element appears in the tuple
index() Returns the index of the first occurance of a given element in the tuple
Takes elements in the tuple and returns a new sorted list. It should be noted that,
sorted()
sorted() does not make any change to the original tuple
min() Returns minimum smallest element of the tuple
max() Returns maximum or largest element of the tuple
sum() Returns sum of the elements of the tuple
12
Page
D0CTIONARY
Dictionary is an unordered collection of data values that store the key : value pair instead of
single value as an element . Keys of adictionary must be unique and of immutable data types
such as strings, tuples etc. Dictionaries are also called mappings or hashes or associative
arrays

Creating a Dictionary
Tocreate a dictionary in Python, key value pair is used
Dictionary is list in curly brackets, inside these curly brackets,keys and values are declared.
Syntax dictionary_name = { keyl:valuel. kev2: value2.. Each key is separated from its
value by a colon (:) while each element is separated by commas
>>> Employees ={"Abhi " : " Manger " " Manish ""Project Manager", " Aasha ":"
Analyst ". " Deepak" :" Programmer "," Ishika ":" Tester "}
Accessing elements from a Dictionary
Syntax: dictionary_name[keys]
>>> Employees[' Aasha ]
'Analyst
Traversing a Dictionary
1. Iterate through all keys 2. Iterate through allvalues
>>>for iin Employees: >>> for i in Employees:
print(i) print(Employees[i)
Output:
Output: Manger
Abhi
Manish Project Manager
Aasha Analyst
Programmer
Deepak Tester
Ishika
3. Iterate through key and values 4. Iterate through key and values simultaneously
>>> for iin Employees: >>> for a,b in Employees. items(0:
print(i, ": ", Employees[i1) print("Key = ".a," and respective value =",b)
Output: Output:
Abhi : Manger Key = Abhi and respective value = Manger
Manish : Project Manager Key = Manish and respective value = Project Manager
Aasha : Analyst Key = Aasha and respective value = Analyst
Deepak : Programmer Key =Deepak and respective value =Programmer
Ishika :Tester Key = Ishika and respective value = Tester
Adding elements to a Dictionary
Syntax: dictionary_name[new key]=value
>>> Employees['Neha'] = "HR"
>>> Employees
Abhi ':" Manger,' Manish ':'Project Manager"," Aasha ':" Analyst', ' Deepak ':"
Programmer,'Ishika ': Tester Neha': 'HR'}
Updating elements in a Dictionary
Syntax: dictionary_name[existing key] =value
>>> Employees['Neha'] ="Progammer "
>>> Employees
(Abhi':"Manger",'Manish ':'Project Manager',' Aasha':'Analyst ','Deepak ': "
Programmer', "Ishika':"Tester', Neha':'Progammer'}
Membership operators in Dictionary
Two membership operators are in and not in. The membership operator inchecks ifthe key is
Page13 present in the dictionary
>>>" Ishika "in Employees >>>'Analyst 'not in Employees
True True
BUILT IN DÊCTIONARY METHODS
Metho Description

len() Returns the length or number of key: value pairs of the dictionary
dict() Creates a dictionary from a sequence of key-value pairs
Returns a list of keys inthe dictionary
keys) Returns a list of values in the dictionary
values()
items() Returns a list of tuples(key - value) pair
as the argument
Returnsthe value correspondingto the key passedreturn
get() None
will
Ifthe key is not present in the dictionary it passed as the argument to the key
update() appends the key-value pair of the dictionary
value pair of the given dictionary
the dictionary from the memory we
del) Deletes the item withthe given key To delete
write: del Dict name
clear() Deletes or clear allthe items of the dictionary

MIND MAP
Method
DList is an ordered sequence len()
of heterogeneous elements list()
DList is created using [] append)
bracket extend()
Individual character in a list insert()
can be assessed using index count()
Lists are mutable index()
remove()
List Osperations LIST pop)
reverse()
D Concatination Operator ()
sort()
OReplication Operators (*) sorted()
DComparison Operators (= min()
>,<,<=,>=,!5)
Membership Operators (in max)
sum)
& not in
Listsupports slicing

O Tuple is an ordered sequence of


heterogeneous elements
Method
OTuple is created using () bracket
Individual character in a tuple len()
can be assessed using index tuple()
Tuples are immutable count)
TUPLE index)
Tuple Operations sorted)
O Concatination Operator () min()
O Replication Operators (") max()
OComparison Operators( , < sum)
Page14
Membership Operators (in & not in
upes supports slicing
MIND MAP

Method
D Dictionary is an unordered
collection of data values that store len()
the key :value pair dict)
OKeys of a dictionary must be keys)
unique and of immutable data types DICTIONARY values()
ODictionary is created using {} items()
bracket
get)
Individual character in a dictionary update)
can be assessed using keys
Membership Operators (in & not in del()
checks ifthe key is present in the clear()
dictionary

Method
OEnclosed by single, double or len)
triple quotes title()
Individual character in a string lower()
can be assessed using index upper()
O Strings are immutable count(str, start, end)
find(str,start, end)
index(str, start, end)
STRING endswith)
startswith)
isalnum()
String Operations islower()
D Concatination Operator isupper()
() isspace)
D Replication Operators istitle)
() Istrip)
DComparison Operators ( rstrip)
=,>,<,<F,>=, strip)
replace(oldstr, newstr)
Membership Operators join)
(in &not in partition(0)
String supports slicing split)

QUESTIONS:
IMARK QUESTIONS
1. What will be the output of the following set of commands
>>> str ="hello"
>>> str[:2]
a. lo b. he c. llo d. el
2. Which type of object is given below
>>>L= 1,23,"hello", I
a. list b. dictionary c. array d. tuple
Page15 3. Which operator tells whether an element is present in a sequence or not
a. exist b. in c. into d. inside

You might also like