Unit -II String, Lists, Dict, Tuple, Sets
Unit -II String, Lists, Dict, Tuple, Sets
String Slicing and Joining
String slices :
A segment or a portion of a string is called as slice
extracted from a string using colon (:)
The basic syntax for slicing a string :
Ex1:
#string slice
s='hello python'
s[0:7]
Output:
'hello p'
Continue.
#slice2
fruit='banana'
fruit[:3]
Output:
'ban‘
---------------------
Continue..
#slice3
fruit='banana'
fruit[3:]
Output:
'ana‘
-----
#slice3
fruit='banana'
fruit[3:3]
Output: ‘’
Strings are immutable
Once strings are created cant be changed.
String concatenating
Joining together
+ operator
Example:
#string concatenation
str1='hello'
str2='python'
str3=str1+str2
print("the concatenated string is:",str3)
Output:
the concatenated string is: hellopython
example2
#concat 2 strings
string1 = input("enter the first string")
string2 = input("enter the second string“)
full_name = string1 + " " + string2
print(full_name)
example3
#error_example
cost = 15
string1 = "The total in Euro is: “
bill = string1 + cost
print(bill)
Error message
TypeError Traceback (most recent call last)
<ipython-input-6-bdea940ccf25>
in <module> 2
string1 = "The total in Euro is: "
bill = string1 + cost
print(bill)
TypeError: can only concatenate str (not "int") to str
correction
#correct code
cost = 15
string1 = "The total in Euro is:”
bill = string1 + str(cost)
print(bill)
----------------
Output:
The total in Euro is: 15
String append
Add something at the end.
+= operator used
upper():
word. upper()
example
#coverting upper case
word='banana'
new_word=word.upper()
print(new_word)
Output:
BANANA
find()
#coverting upper case
word='banana'
index=word.find('n')
print(index)
Output:
2
Built in functiuons
str.capitalize():
returns a copy of the string with its first
character capitalized.
Example:
str.capitalize('cookie')
Cookie
str.islower():
returns true if all characters in the string are
lowercase, false otherwise.
Example:
snack = 'cookie'
snack.islower()
Method Description
Converts the first character
capitalize()
to upper case
center() Returns a centered string
Returns the number of times
count() a specified value occurs in a
string
Returns an encoded version
encode()
of the string
Method Description
Adds an element at the end of
append()
the list
Removes all the elements from
clear()
the list
copy() Returns a copy of the list
Returns the number of elements
count()
with the specified value
Add the elements of a list (or
extend() any iterable), to the end of the
current list
Returns the index of the first
index()
element with the specified value
Adds an element at the specified
insert()
position
Removes the element at the
pop()
specified position
Removes the first item with the
remove()
specified value
#remove punctuation
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
List slicing
Expression : list [ begin : end : step ]
Begin : defaults to 0, end : defaults to the length of the list, step: default is 1.
Left side of an assignment can update multiple elements
t = ['a','b','c','d','e','f']
t[1:3] = ['x', 'y']
print(t) //['a', 'x', 'y', 'd', 'e', 'f']
lst =[10,20,30,40,50,60,70,80,90,100]
print(lst) print(lst[:])
print(lst[0:3]) print(lst[-100:3])
print(lst[4:8]) print(lst[4:100])
print(lst[2:5]) print(lst[2:-2:2])
print(lst[-5:-3]) print(lst[::2])
print(lst[:3])
print(lst[4:])
Built In Functions:
Len : returns the number of items in the list
Sum : returns the sum of the items in the list
Min : returns the minimum of the items in the list
Max : returns the maximum of the items in the list
List Methods
append : adds a single item to the existing list
extend : takes a single argument (a list) and adds it to the end.
Count : returns the number of times a given element appears in the list
Insert : new element before the element at a given index. Modifies
//ls.insert(1,"hi")
index : Returns the lowest index
Reverse : reverses the elements in the list. Modifies.
Sort : ascending order. Modifies
Clear : removes all the elements, list empty
Deleting Elements: several ways to delete elements
pop() : removes the item at specified index p and returns its value
remove():if the index of the element is not known, then the value to be removed can be
specified, will not return the value
del : when more than one item to be deleted at a time || del my_list[1:5]
Sets
Python provides a data structure that represents a
mathematical set
we use curly braces { }
Are unordered and may contain no duplicate
elements
Duplicate elements appear only once in the set
The expression { } does not represent the empty
set.
Set must contain at least one element.
Creation of sets
>>> s = {10, 3, 7, 2, 11}
>>> s {2, 11, 3, 10, 7}
>>> t = {5, 4, 5, 2, 4, 9}
>>> t {9, 2, 4, 5}
s={10,20,30,40}
s={10,20,2.3,”abc”}
s={10,20,30,20,10,20,10}
s[1] //We cannot access element using index
s={10,20}
s.add(30)
print(s)
s.discard(20)
print(s)
List conversion using set()
>>> l = [10, 13, 10, 5, 6, 13, 2, 10, 5]
>>> s = set(l)
>>> s
{10, 2, 13, 5, 6}
program:
#duplicated allows
thistuple = ("apple", "banana", "cherry", "apple",
"cherry")
print(thistuple)
('apple', 'banana', 'cherry', 'apple', 'cherry')
Tuple Length
#Print the number of items in the tuple
thistuple = ("apple", "banana", "cherry")
print("the length of given tuple :",len(thistuple))
-----------------------
output:
the length of given tuple is: 3
data type of tuples
#checking data type
thistuple = ("apple",)
print(type(thistuple))
----------------------------
<class 'tuple'>
not a tuple
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
---------------------------
output:
<class 'str'>
example
#example String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
Output:
print(tuple2)
print(tuple3) ('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
slice in tuple
#use of slice operation in tuple
tup1=(1,2,3,4,5,6,7,8,9,10)
print("tup1[3:6]=",tup1[3:6])
print("tup1[:8]=",tup1[:8])
print("tup1[4:]=",tup1[4:]) Output:
print("tup1[:]=",tup1[:]) tup1[3:6]= (4, 5, 6)
tup1[:8]= (1, 2, 3, 4, 5, 6, 7, 8)
tup1[4:]= (5, 6, 7, 8, 9, 10)
tup1[:]= (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
updating tuple
only extract values from a tuple to form another tuple.
d={10:"A",20:"A",30:"A"} print(d)
Update()
d.update({"abc":302})
Traversing:
for k in d.keys():
print(k)
for v in d.values():
print(v)