0% found this document useful (0 votes)
14 views

Python-Unit2

Uploaded by

bhumikaksa16
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python-Unit2

Uploaded by

bhumikaksa16
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Unit-2: Strings and

Lists
Strings
• A string is a sequence of characters. You can access the characters
one at a time with the bracket operator. [ ]
• Strings are used in different applications such as:
• Natural language Processing.
• Regular expression.
• Data mining.
• Dictionaries.
• Chatbot.
• Machine translation.
sub=“Python”
Using Strings
Fruit= “banana”
- Fruit is now a string object.
- Every character in a string has a index value which starts from 0.
- When accessing the string characters, we make use of indices inside
the square brackets. For ex: Fruit[0] is b, Fruit[1] is a …….
- Index is always an integer number. It can be a variable or an
expression.
Getting the length of a string
• The len() function.
• Ex:
length= len(Fruit)
- The output is 6.
- But Fruit[6] is an error, as the index for “banana” starts at 0 and ends
at 5.
- To get the last character, use Fruit[length-1]
- Alternatively, negative indices can also be used.
- Fruit[-1],Fruit[-2]….
String Traversal using loops
• Using a while loop.
Using a for loop
String slicing
• A segment of a string is called a slice. Selecting a slice can be done
using the character ‘:’
Strings are immutable
• String objects once created cannot be altered or changed at any point
in the program.

• S= “Jello”
• S[0]=‘H’ # Error
• Solution:
S1=‘H’+S[1:]
Looping and Counting
• Counting number of characters in a string
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(“count of a’s:”, count)
The in operator
• in is a Boolean operator that takes 2 strings, returns True if the first
string appears as a substring of second string.
• Ex:
‘s’ in ‘words’ #True
‘ors’ in ‘words’ #False
• not in will return True if the first string does not appear in the second.
String Comparison
• The comparison operator ‘==‘ works on strings also.
• Other comparison operators such as <,> can also be used.
They compare the ASCII values of the first character of the
strings.
Strings Methods
• Every object in python is associated with data and methods.
Methods are built into the object and are available to any
instance of that object.
• The function dir() shows all the available methods for that
object.
s=“python”
dir(s)

• Calling a method or method invocation is done using the dot


operator.
object_name/variable_name.method_name()
String Methods
• s=“banana”
• s.upper()
• s.lower()
• s.find(sub-string,from_pos,to_pos)
• s.strip(characters)
• s.startswith(‘pattern’)
• s.endswith(‘pattern’)
• s.count(‘pattern’)
• s.replace(‘old’,’new’,count)
Parsing Strings
• Given a series of e-mail addresses, followed by date and time of
email sent, find out the domain which they belong to.
• For ex:
From: [email protected] Sat, Jul 1 2012
From: [email protected] Mon, Jul 3 2013

Data=“From: [email protected] Sat, Jul 1 2012”


atpos=Data.find(‘@’)
sppos=Data.find(‘ ’,atpos)
domain=Data[atpos+1:sppos]
print(domain)
Programs
• Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the colon character
and then use the float function to convert the extracted string into a floating point
number.
• Write a Python program to calculate the length of a string without using built-in
function.
• Write a program that accepts a string from user. Your program should count and
display number of vowels in that string.
• Write a Python program to compare two strings and if the strings are equal, True
should be printed or else False should be printed.
• Write a Python program to iterate through a string and check whether a particular
character is present or not. If present, true should be printed otherwise, false should
be printed.
• Write a program in Python to convert a word from lower case to upper case and
display the number of letters in that word.
Lists
• A list is a sequence of values that may belong to any type.
The values in the list are called as elements or items.
fruits=[‘apple’,’mango’,’banana’]
Roll_nos=[102,110,123]
The above lists are having values of the same type. Hence,
they are homogeneous lists.
- However, a list can store values of different types, called
heterogeneous lists.
Ex: list1=[‘red’, 2022, 25.7]
List2=[10,30,list1]
Nested Lists
• One list embedded inside another list is called as nested list.
• In this case, the entire inner list is treated as a single
element.
• The in operator and comparison operators work on lists too.
Lists are Mutable
• Lists are mutable types in python. It means, we can change
the values in the list once it is created.
• For ex:
list1=[20,25,30]
list1[0]=15
Mapping: A list can be thought of a relationship between
index and element. This relationship is called mapping.
- The list indices work in a similar way as strings.
List Traversal
• Using for loop
1) ls1=[100,200,300]
for i in ls1:
print(i)
2) ls1=[100,200,300]
for i in range(len(ls1)):
ls1[i]=ls1[i]*10
List Operations
• The + operator is used to join 2 lists.
List1=[100,200,300]
List2=[‘apple’, ‘banana’]
L3=List1+List2
print(L3)
• The * operator is used to repeat the list n times.
List Slices
• The slicing operator is ‘:’
• Ex:
A=[‘a’,’b’,’c’,’d’]
A[1:3]
#output: [‘b’,’c’]
Syntax: List_name[start:stop:step]
a[1:3]=[‘x’,’y’]
List indexing in nested list
• List1=[1,2,3,[10,20]]
List[0] -> 1
List[3]-> [10,20]
List[3][0]->10
List[3][1]->20
Therefore, we need two indices to access the element in the
nested list.
• Write a program to find the average of all list elements.
• Write a Python program to get the largest number from a list
of numbers entered by user.
• Find the difference between 2 lists.
• Find the union of 2 lists.
• Reverse a given list elements.
List Methods
1. list1.append(): Adds an element at the end of the list.
Syntax: list_name.append(element)
2. list1.clear(): Clears all the elements in the list and makes it empty.
3. x= list1.copy(): Copies the elements from list1 to x.
4. list1.count(element): Returns the count of number of times the
element occurs in the list.
5. list1.extend(list2): Appends the elements of list2 at the end of
list1.
Difference between append() and extend()??
Difference between extend() and + operator??
(extend() can be used with any iterable object)
6. list1.index(element): Returns the index of the element in the list.
7. list1.insert(pos, element): Used to insert an element at a specified
position in the list.
8. list1.pop(pos): Used to remove the element present at a specified
position in the list. If pos is not given, it removes the last element.
9. list1.remove(element): Used to remove a specific element from the
list.
10.list1.reverse(): Used to reverse the contents of a given list.
11. list1.sort(): Sort the contents of a given list. (Considers ASCII values
when elements are of string type).
The del Operator
• The del operator is a special operator in python that deletes
one or more elements from the list.
t=[1,2,3,4,5]
del t[1]
print(t)
- Removing multiple elements:
del t[1:3]
print(t)
Lists and Functions
• There are some python built-in functions that can be used with lists.
• 1. len(): Gives the number of elements in the list.
• 2. max(): Returns the maximum element in the list.
• 3. min(): Returns the minimum element in the list.
• 4. sum(): Returns the sum of elements in the list. Works only with
integer lists.
- Write a program to find the sum and average of the list elements.
Lists and Strings
• A string is a sequence of characters, and a list is a sequence of values.
• To convert from a string to a list of characters, we use the list()
constructor.
Ex: s=“python”
t= list(s)
print(t)
#output: [‘p’,’y’,’t’,’h’,’o’,’n’]

- Another way to convert a string to list?


s=“Hello, how are you?”
t=s.split()
Lists to strings
• We can convert list elements into a string using the join()
function.
• We need a joining character called delimiter.
Ex: list1=[‘hello’,’how’,’are’,’you’,’doing’]
delim=‘ ‘
s=delim.join(list1)
Parsing Lines
From [email protected] Fri Jun 20 5:20:12 2023
From [email protected] Sat Jun 20 5:20:12 2023
From [email protected] Mon Jun 20 5:20:12 2023

- Specific information can be easily extracted from the lines


above using split() method.
Objects and Values
• Consider the below objects:
a=“banana”
b=“banana”

a=[1,2,3]
b=[1,2,3]
Here, a and b are 2 different objects.
Object Aliasing
• The same object may be called by different names.
• Write a program to check if the given key is present in the
list, if yes, print its position.
• Write a program to remove duplicates from a list.
• Consider the given scenario: In a bank, a cashier is serving a
queue of customers with token number starting from 101.
There are 20 customers standing in the queue. The cashier is
a slow server and takes 5 mins to serve each customer. To
avoid waiting time, the manager appoints another cashier
who serves only even token numbers. Now the first cashier
serves odd token numbers and second, the even ones. Write
a program to create 2 queues of customers and cashiers
serve them in the increasing order of token numbers.

You might also like