SlideShare a Scribd company logo
UNIT 4
String
String
• A string is a sequence of characters.
• Computers do not deal with characters, they deal with
numbers (binary). Even though you may see characters
on your screen, internally it is stored and manipulated as
a combination of 0s and 1s.
• This conversion of character to a number is called
encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encodings used.
How to create a string in Python?
• Strings can be created by enclosing characters inside a
single quote or double-quotes. Even triple quotes can be
used in Python but generally used to represent multiline
strings and docstrings.
Syntax:
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
To access characters in a string
• We can access individual characters using indexing and a
range of characters using slicing. Index starts from 0.
• Trying to access a character out of index range will raise
an IndexError. The index must be an integer. We can't use
floats or other types, this will result into TypeError.
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second
last item and so on.
Slicing Operator
• We can access a range of items in a string by using the slicing operator
:(colon).
#Accessing string characters in Python
str = 'PythonProgramming'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Deletion updation in a string
• Strings are immutable. This means that elements of a
string cannot be changed once they have been assigned.
We can simply reassign different strings to the same
name.
• Example:
my_string='Python'
my_string[5]='a'
print(my_string)
• We cannot delete or remove characters from a string. But
deleting the string entirely is possible using the del
keyword.
• Example:
my_string='Python'
print(my_string)
del my_string[2]
• Item deletion is not possible but a complete can be
deleted with del keyword.
• Example:
my_string='Python'
print(my_string)
del my_string
print(my_string)
Reversing a Python String
• With Accessing Characters from a string, we can also
reverse them. We can Reverse a string by writing [::-1]
and the string will be reversed.
• Example:
my_string='Python'
#this will print simple string
print(my_string)
#now we will print the reversed string
print(my_string[::-1])
• We can also reverse a string by using built-in join and
reversed function.
• Example:
my_string='Python'
rev="".join(reversed(my_string))
print(rev)
String Operators
Python String Formatting
1. Escape Sequence:
Let's suppose we need to write the text as - They said, "Hello what's going
on?"- the given statement can be written in single quotes or double quotes but it
will raise the SyntaxError as it contains both single and double-quotes.
Example:
str = "They said, "Hello what's going on?""
print(str)
• We can use the triple quotes to accomplish this problem
but Python provides the escape sequence.
• The backslash(/) symbol denotes the escape sequence.
The backslash can be followed by a special character and
it interpreted differently. The single quotes inside the
string must be escaped. We can apply the same as in the
double quotes.
Example
# using triple quotes
print('''''They said, "What's there?"''')
# escaping single quotes
print('They said, "What's going on?"')
# escaping double quotes
print("They said, "What's going on?"")
escape character n
• n it is used for providing 'new line'
Let us consider an example:
print("hellonpython") # will print result as follows
hello
python
•  it is used to represent backslash:
print("hellohow are you") # will print result as follows
hellohow are you
• It returns one single backslash.
• ' it is used to print a Single Quote( ' ).
print("It's very powerful") # will print result as follows
It's very powerful
• " it is used to represent double Quote( " )
print("We can represent Strings using " ") # will print result as follows
We can represent Strings using "
• t it is used to provide a tab space
print("HellotPython") # will print result as follows
Hello Python
repr()
• Some times we want the escape sequence to be printed as it is
without being interpreted as special.
• When using with repr() or r or R, the interpreter treats the escape
sequences as normal strings so interpreter prints these escape
sequences as string in output. We use repr(), the built-in method
to print escape characters without being interpreted as special .
• We can also use both 'r'and 'R'. Internally they called repr()
method.
Example
• Let us take a simple example using repr()
str = "HellotPythonnPython is very interesting"
print(str) # will print result as follows
Hello Python
Python is very interesting
print(repr(str))# will print result as follows
'HellotPythonnPython is very interesting'
• Let us consider another example using 'r' and 'R'.
print(r"HellotPythonnPython is very interesting") # will print result as
follows
HellotPythonnPython is very interesting
print(R"HellotPythonnPython is very interesting") # will print result as
follows
HellotPythonnPython is very interesting
Built-in String Methods
• Python provides the following built-in string methods
(operations that can be performed with string objects)
• The syntax to execute these methods is:
stringobject.methodname()
String lower() Method
• Python String lower() method converts all uppercase characters in
a string into lowercase characters and returns it.
• Example:
text="Hi there"
print(text.lower())
• capitalize() function is used to capitalize first letter of string.
• upper() function is used to change entire string to upper case.
• title() is used to change string to title case i.e. first characters of all
the words of string are capitalized.
• swapcase() is used to change lowercase characters into
uppercase and vice versa.
• split() is used to returns a list of words separated by
space.
• center(width,"fillchar") function is used to pad the string
with the specified fillchar till the length is equal to width.
Count()
• count() returns the number of occurrences of substring in
particular string. If the substring does not exist, it returns
zero.
• Example:
a = "happy married life happy birthday birthday "
print(a.count('happy'))
• replace(old, new), this method replaces all old substrings
with new substrings. If the old substring does not exist, no
modifications are done.
a = "java is simple"
print(a.replace('java' ,'Python')) # will print result as follows
'Python is simple'
• Here java word is replaced with Python.
Note
• The original string is left intact. Strings are immutable in
Python. As you can see, the replace method doesn't
change the value of the string t1 itself. It just returns a
new string that can be used for other purposes
Join()
• join() returns a string concatenated with the elements of
an iterable. (Here “L1” is iterable)
b = '.'
L1 = ["www", "codetantra", "com"]
print(b.join(L1)) # will print result as follows
'www.codetantra.com'
• Here '.' symbol is concatenated or joined with every item
of the list.
isupper()
• isupper() function is used to check whether all characters
(letters) of a string are uppercase or not.
• If all characters are uppercase then returns True,
otherwise False.
a = 'Python is simple'
print(a.isupper())
>>>False
islower()
• islower() is used to check whether all characters (letters)
of a string are lowercase or not.
• If all the letters of the string are lower case then it returns
True otherwise False.
a = "python"
print(a.islower())
>>>True
isalpha()
• isalpha() is used to check whether a string consists of
alphabetic characters only or not.
• If the string contains only alphabets then it returns True
otherwise False.
a = "hello programmer"
print(a.isalpha())
>>>False
b = "helloprogrammer"
print(a.isalpha())
>>>True
• Note: Space is not considered as alphabet character, it comes in
the category of special characters.
isalnum()
• isalnum() is used to check whether a string consists of
alphanumeric characters.
• Return True if all characters in the string are alphanumeric and
there is at least one character, False otherwise.
• Note:
Characters those are not alphanumeric are: (space) ! # % & ?
etc.
Numerals 0 through 9 as well as the alphabets A - Z
(uppercase and lowercase) came into the category of
alphanumeric characters.
isdigit()
• isdigit() is used to check whether a string consists of
digits only or not. If the string contains only digits then it
returns True, otherwise False.
a = "123"
print(a.isdigit()) # will print result as follows
True
• Here the string 'a' contains only digits so it returns True.
isspace()
• isspace() checks whether a string consists of spaces only
or not. If it contains only white spaces then it returns True
otherwise False.
a = " "
print(a.isspace()) # will print the result as follows
True
• Here the string 'a' contains only white spaces so it returns
True.
istitle()
istitle() checks whether every word of a string starts with
upper case letter or not.
a = "Hello Python"
print(a.istitle()) # will print the result as follows
True
startswith(substring)
• startswith(substring) checks whether the main string
starts with given sub string. If yes it returns True,
otherwise False.
a = "hello python"
print(a.startswith('h')) # will print result as follows
True
endswith(substring)
• endswith(substring) checks whether the string ends with
the substring or not.
a = "hello python"
print(a.endswith('n')) # will print result as follows
True
find(substring)
• find(substring) returns the index of the first occurrence of
the substring, if it is found, otherwise it returns -1
a = "hello python"
print(a.find('py')) # will print result as follows
6
len(a)
• len(a) returns the length of the string.
a = 'hello python'
print(len(a)) # will print result as follows
12
min(a)
• min(a) returns the minimum character in the string
a = "Hello Python"
print(min(a)) # will print result as follows# min(a) prints
space because space is minimum value in Hello
Python.
• Here it returns white space because in the given string
white space is the minimum of all characters.
max(a)
• max(a) returns the maximum character in the string.
print(max(a)) # will print result as follows
y
Lists
• Python lists are one of the most versatile data types that
allow us to work with multiple elements at once.
• In Python, a list is created by placing elements inside
square brackets [], separated by commas.
# list of integers
my_list = [1, 2, 3]
• A list can have any number of items and they may be of
different types (integer, float, string, etc.).
# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
Nested List
• A list can also have another list as an item. This is called
a nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Access List Elements
• We can use the index operator [] to access an item in a
list. In Python, indices start at 0. So, a list having 5
elements will have an index from 0 to 4.
• Trying to access indexes other than these will raise an
IndexError. The index must be an integer. We can't use
float or other types, this will result in TypeError.
my_list = ['p', 'r', 'o', 'b', 'e']
# first item
print(my_list[0]) # p
# third item
print(my_list[2]) # o
# fifth item
print(my_list[4]) # e
• Nested lists are accessed using nested indexing.
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
Negative indexing
• Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last
item and so on.
# Negative indexing in lists
my_list = ['p','r','o','b','e']
# last item
print(my_list[-1])
# fifth last item
print(my_list[-5])
List Slicing in Python
• We can access a range of items in a list by using the slicing operator :.
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements from index 2 to index 4
print(my_list[2:5])
# elements from index 5 to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
• Note: When we slice lists, the start index is inclusive but
the end index is exclusive. For example, my_list[2: 5]
returns a list with elements at index 2, 3 and 4, but not 5.
Update List Elements
• Lists are mutable, meaning their elements can be
changed unlike string or tuple.
• We can use the assignment operator = to change an item
or a range of items.
Example
# Updating values in a list
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
print(odd)
extend()
• We can add one item to a list using the append() method
or add several items using the extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.extend([9, 11, 13])
print(odd)
list concatenation and repeat
• We can also use + operator to combine two lists. This is
also called concatenation.
• The * operator repeats a list for the given number of
times.
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5])
print(["re"] * 3)
insert()
• we can insert one item at a desired location by using the
method insert() or insert multiple items by squeezing it
into an empty slice of a list.
• # Example of list insert() method
• odd = [1, 9]
• odd.insert(1,3)
• print(odd)
• odd[2:2] = [5, 7]
• print(odd)
Delete List Elements
• We can delete one or more items from a list using the
Python del statement. It can even delete the list entirely.
Example
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
# delete the entire list
del my_list
remove(), pop(), and clear()
• We can use remove() to remove the given item or pop() to
remove an item at the given index.
• The pop() method removes and returns the last item if the
index is not provided. This helps us implement lists as
stacks (first in, last out data structure).
• And, if we have to empty the whole list, we can use the
clear() method.
Example
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear()
# Output: []
print(my_list)
Python List Methods
• Python has many useful list methods that makes it really
easy to work with lists. Here are some of the commonly
used list methods.
1. append() adds an element to the end of the list
2. extend() adds all elements of a list to another list
3. insert() inserts an item at the defined index
4. remove() removes an item from the list
5. pop() returns and removes an element at the given index
6. clear() removes all items from the list
7. index() returns the index of the first matched item
8. count() returns the count of the number of items passed as
an argument
9. sort() sort items in a list in ascending order
10. reverse() reverse the order of items in the list
11. copy() returns a shallow copy of the list
Example
# Example on Python list methods
my_list = [3, 8, 1, 6, 8, 8, 4]
# Add 'a' to the end
my_list.append('a')
# Output: [3, 8, 1, 6, 8, 8, 4, 'a']
print(my_list)
# Index of first occurrence of 8
print(my_list.index(8)) # Output: 1
# Count of 8 in the list
print(my_list.count(8)) # Output: 3
List Membership Test
• We can test if an item exists in a list or not, using the
keyword in.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
Iterating Through a List
• Using a for loop we can iterate through each item in a list.
for fruit in ['apple','banana','mango']:
print("I like",fruit)
list()
• This function converts an iterable (tuple, string, set,
dictionary) to a list
• Example:
print(list("abcdef"))
['a', 'b', 'c', 'd', 'e', 'f']
print(list(('a', 'b', 'c', 'd', 'e')))
['a', 'b', 'c', 'd', 'e']
Some other built-in list methods
• all()
• any()
• enumerate()
• len()
• max()
• min()
• sorted()
• sum()
Tuple
Tuple
• A tuple in Python is similar to a list. The difference
between the two is that we cannot change the elements of
a tuple once it is assigned whereas we can change the
elements of a list.
Creating a Tuple
• A tuple is created by placing all the items (elements)
inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to
use them.
• A tuple can have any number of items and they may be of
different types (integer, float, list, string, etc.).
Types of tuple
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Tuple Packing
• A tuple can also be created without using parentheses.
This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
• Creating a tuple with one element is a bit tricky.
• Having one element within parentheses is not enough.
We will need a trailing comma to indicate that it is, in fact,
a tuple.
Example
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Access Tuple Elements with indexes
• We can use the index operator [] to access an item in a tuple, where the
index starts from 0.
• So, a tuple having 6 elements will have indices from 0 to 5. Trying to access
an index outside of the tuple index range(6,7,... in this example) will raise an
IndexError.
• The index must be an integer, so we cannot use float or other types. This will
result in TypeError.
• Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
Example
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second
last item and so on.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Slicing
• We can access a range of items in a tuple by using the
slicing operator colon (:).
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
print(my_tuple[1:4])
# elements 8th to end
print(my_tuple[7:])
# elements beginning to end
print(my_tuple[:])
Changing a Tuple
• Unlike lists, tuples are immutable.
• This means that elements of a tuple cannot be changed once they
have been assigned. But, if the element is itself a mutable data
type like a list, its nested items can be changed.
• We can also assign a tuple to different values (reassignment).
Example
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# my_tuple[1] = 9
# TypeError: 'tuple' object does not support item assignment
# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
concatenation and repeat
• We can use + operator to combine two tuples. This is
called concatenation.
• We can also repeat the elements in a tuple for a given
number of times using the * operator.
• Both + and * operations result in a new tuple.
Example
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Deleting a Tuple
• we cannot change the elements in a tuple. It means that
we cannot delete or remove items from a tuple.
• Deleting a tuple entirely, however, is possible using the
keyword del.
Example
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# del my_tuple[3]
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# Can delete an entire tuple
del my_tuple
print(my_tuple)
# NameError: name 'my_tuple' is not defined
Tuple Methods
• Methods that add items or remove items are not available
with tuple.
• Only the following two methods are available.
1. count()
2. index()
Example
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
Tuple Membership Test
• We can test if an item exists in a tuple or not, using the keyword in.
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Iterating through tuple
• We can use a for loop to iterate through each item in a
tuple.
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)
Advantages of Tuple over List
• We generally use tuples for heterogeneous (different)
data types and lists for homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is
faster than with list. So there is a slight performance
boost.
• Tuples that contain immutable elements can be used as a
key for a dictionary. With lists, this is not possible.
• If you have data that doesn't change, implementing it as
tuple will guarantee that it remains write-protected.
Built-in tuple functions
• enumerate(): Returns an enumerate object consisting of
the index and value of all items of a tuple as pairs
• Example
x = (1, 2, 3, 4, 5, 6)
print(tuple(enumerate(x)))
>>> ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6))
len()
• This function calculates the length i.e., the number
elements in the tuple
• Example:
x = (1, 2, 3, 4, 5, 6)
print(len(x))
>>> 6
max() & min()
• max(): This function returns the item with the highest
value in the tuple.
print(max((1, 2, 3, 4, 5, 6)))
>>> 6
• min(): This function returns the item with the lowest value
in the tuple.
print(min((1, 2, 3, 4, 5, 6)))
sorted()
• This function returns a sorted result of the tuple which is a
list, with the original tuple unchanged.
• Example:
origtup = (1, 5, 3, 4, 7, 9, 1, 27)
sorttup = sorted(origtup)
print(sorttup)
>>> [1, 1, 3, 4, 5, 7, 9, 27]
print(origtup)
>>> (1, 5, 3, 4, 7, 9, 1, 27)
sum()
• This function returns the sum of all elements in the tuple.
• This function works only on numeric values in the tuple and will
error out if the tuple contains a mix of string and numeric values.
• Example:
print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
57
print(sum((1, 3, 5, 'a', 'b', 4, 6, 7)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
tuple()
• This function converts an iterable (list, string, set,
dictionary) to a tuple
• Example:
x = list("abcdef")
print(x)
['a', 'b', 'c', 'd', 'e', 'f']
print(tuple(x))
('a', 'b', 'c', 'd', 'e', 'f')
Dictionary
Dictionary
• Dictionary in Python is a collection of keys values, used to
store data values like a map, which, unlike other data
types which hold only a single value as an element.
• Dictionary holds key:value pair. Key-Value is provided in
the dictionary to make it more optimized.
• we can create a dictionary using the built-in dict() function
as well.
Creating Python Dictionary
• A dictionary can be created by placing a sequence of elements
within curly {} braces, separated by ‘comma’. Dictionary holds
pairs of values, one being the Key and the other corresponding
pair element being its Key:value. Values in a dictionary can be of
any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable.
• Note – Dictionary keys are case sensitive, the same name but
different cases of Key will be treated distinctly.
Example
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
Accessing Elements from Dictionary
• While indexing is used with other data types to access
values, a dictionary uses keys. Keys can be used either
inside square brackets [] or with the get() method.
• If we use the square brackets [], KeyError is raised in
case a key is not found in the dictionary. On the other
hand, the get() method returns None if the key is not
found.
Example
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name'])
# Output: Jack
print(my_dict.get('age'))
# Output: 26
Updating dictionary elements
• Dictionaries are mutable. We can add new items or
change the value of existing items using an assignment
operator.
• If the key is already present, then the existing value gets
updated. In case the key is not present, a new (key:
value) pair is added to the dictionary.
Example
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
#Output: {'age': 27, 'name': 'Jack'}
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
Removing elements from Dictionary
• We can remove a particular item in a dictionary by using the pop()
method. This method removes an item with the provided key and
returns the value.
• The popitem() method can be used to remove and return an
arbitrary (key, value) item pair from the dictionary. All the items
can be removed at once, using the clear() method.
• We can also use the del keyword to remove individual items or
the entire dictionary itself.
Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
print(squares.pop(4))
# Output: 16
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
# remove an arbitrary item, return (key,value)
print(squares.popitem())
# Output: (5, 25)
print(squares)
# Output: {1: 1, 2: 4, 3: 9}
Example (Continues..)
# remove all items
squares.clear()
print(squares)
# Output: {}
# delete the dictionary itself
del squares
print(squares)
# Throws Error
Python Dictionary Methods
• clear(): Removes all items from the dictionary.
• copy(): Returns a shallow copy of the dictionary.
• fromkeys(sequence,value): Returns a new dictionary with keys
from seq and value equal to v (defaults to None).
• get(key,default=None): Returns the value of the key. If the key
does not exist, returns d (defaults to None).
• items(): Return a new object of the dictionary's items in (key,
value) format.
• keys(): Returns a new object of the dictionary's keys.
• pop(key): Removes the item with the key and returns its value or d if key is
not found. If d is not provided and the key is not found, it raises KeyError.
• popitem(): Removes and returns an arbitrary item (key, value). Raises
KeyError if the dictionary is empty.
• setdefault(key,default=None): Returns the corresponding value if the key is in
the dictionary. If not, inserts the key with a value of d and returns d (defaults
to None).
• update(dict2): Updates the dictionary with the key/value pairs from other,
overwriting existing keys.
• values(): Returns a new object of the dictionary's values
Example
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
print(marks)
# >>> {'English': 0, 'Math': 0, 'Science': 0}
for item in marks.items():
print(item)
#>>> ('Math', 0)
#>>> ('English', 0)
#>>> ('Science', 0)
print(list(sorted(marks.keys())))
#>>> ['English', 'Math', 'Science']
Dictionary Membership Test
• We can test if a key is in a dictionary or not using the
keyword in. Notice that the membership test is only for the
keys and not for the values.
• Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
# Output: True
Iterating Through a Dictionary
• We can iterate through each key in a dictionary using a
for loop.
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Dictionary Built-in Functions
• all(): Return True if all keys of the dictionary are True (or if the
dictionary is empty).
• any(): Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
• len(): Return the length (the number of items) in the dictionary.
• cmp(): Compares items of two dictionaries. (Not available in
Python 3)
• sorted(): Return a new sorted list of keys in the dictionary.
Example
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
UNIT 4 python.pptx

More Related Content

Similar to UNIT 4 python.pptx

Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
workvishalkumarmahat
 
Python data handling
Python data handlingPython data handling
Python data handling
Prof. Dr. K. Adisesha
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
afsheenfaiq2
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
Tinku91
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Python comments and variables.pptx
Python comments and variables.pptxPython comments and variables.pptx
Python comments and variables.pptx
adityakumawat625
 
PYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptxPYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptx
SoundariyaSathish
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
BG Java EE Course
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 

Similar to UNIT 4 python.pptx (20)

Python ppt
Python pptPython ppt
Python ppt
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
 
Ch09
Ch09Ch09
Ch09
 
Python data handling
Python data handlingPython data handling
Python data handling
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Python comments and variables.pptx
Python comments and variables.pptxPython comments and variables.pptx
Python comments and variables.pptx
 
PYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptxPYTHON PROGRAMMING (2).pptx
PYTHON PROGRAMMING (2).pptx
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 

Recently uploaded

240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf
Madhura TBRC
 
The Journey of an Indie Film - Mark Murphy Director
The Journey of an Indie Film - Mark Murphy DirectorThe Journey of an Indie Film - Mark Murphy Director
The Journey of an Indie Film - Mark Murphy Director
Mark Murphy Director
 
A TO Z INDIA Monthly Magazine - JUNE 2024
A TO Z INDIA Monthly Magazine - JUNE 2024A TO Z INDIA Monthly Magazine - JUNE 2024
A TO Z INDIA Monthly Magazine - JUNE 2024
Indira Srivatsa
 
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
9u08k0x
 
Young Tom Selleck: A Journey Through His Early Years and Rise to Stardom
Young Tom Selleck: A Journey Through His Early Years and Rise to StardomYoung Tom Selleck: A Journey Through His Early Years and Rise to Stardom
Young Tom Selleck: A Journey Through His Early Years and Rise to Stardom
greendigital
 
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdfMaximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
Xtreame HDTV
 
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docxThe Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
Xtreame HDTV
 
Meet Crazyjamjam - A TikTok Sensation | Blog Eternal
Meet Crazyjamjam - A TikTok Sensation | Blog EternalMeet Crazyjamjam - A TikTok Sensation | Blog Eternal
Meet Crazyjamjam - A TikTok Sensation | Blog Eternal
Blog Eternal
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
AITIX LLC
 
The Evolution of Animation in Film - Mark Murphy Director
The Evolution of Animation in Film - Mark Murphy DirectorThe Evolution of Animation in Film - Mark Murphy Director
The Evolution of Animation in Film - Mark Murphy Director
Mark Murphy Director
 
Tom Selleck Net Worth: A Comprehensive Analysis
Tom Selleck Net Worth: A Comprehensive AnalysisTom Selleck Net Worth: A Comprehensive Analysis
Tom Selleck Net Worth: A Comprehensive Analysis
greendigital
 
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdfMatt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
Azura Everhart
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
9u08k0x
 
I Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledgeI Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledge
Sabrina Ricci
 
Christina's Baby Shower Game June 2024.pptx
Christina's Baby Shower Game June 2024.pptxChristina's Baby Shower Game June 2024.pptx
Christina's Baby Shower Game June 2024.pptx
madeline604788
 
Meet Dinah Mattingly – Larry Bird’s Partner in Life and Love
Meet Dinah Mattingly – Larry Bird’s Partner in Life and LoveMeet Dinah Mattingly – Larry Bird’s Partner in Life and Love
Meet Dinah Mattingly – Larry Bird’s Partner in Life and Love
get joys
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
catcabrera
 
Hollywood Actress - The 250 hottest gallery
Hollywood Actress - The 250 hottest galleryHollywood Actress - The 250 hottest gallery
Hollywood Actress - The 250 hottest gallery
Zsolt Nemeth
 
Treasure Hunt Puzzles, Treasure Hunt Puzzles online
Treasure Hunt Puzzles, Treasure Hunt Puzzles onlineTreasure Hunt Puzzles, Treasure Hunt Puzzles online
Treasure Hunt Puzzles, Treasure Hunt Puzzles online
Hidden Treasure Hunts
 
Scandal! Teasers June 2024 on etv Forum.co.za
Scandal! Teasers June 2024 on etv Forum.co.zaScandal! Teasers June 2024 on etv Forum.co.za
Scandal! Teasers June 2024 on etv Forum.co.za
Isaac More
 

Recently uploaded (20)

240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf
 
The Journey of an Indie Film - Mark Murphy Director
The Journey of an Indie Film - Mark Murphy DirectorThe Journey of an Indie Film - Mark Murphy Director
The Journey of an Indie Film - Mark Murphy Director
 
A TO Z INDIA Monthly Magazine - JUNE 2024
A TO Z INDIA Monthly Magazine - JUNE 2024A TO Z INDIA Monthly Magazine - JUNE 2024
A TO Z INDIA Monthly Magazine - JUNE 2024
 
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
 
Young Tom Selleck: A Journey Through His Early Years and Rise to Stardom
Young Tom Selleck: A Journey Through His Early Years and Rise to StardomYoung Tom Selleck: A Journey Through His Early Years and Rise to Stardom
Young Tom Selleck: A Journey Through His Early Years and Rise to Stardom
 
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdfMaximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
Maximizing Your Streaming Experience with XCIPTV- Tips for 2024.pdf
 
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docxThe Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
 
Meet Crazyjamjam - A TikTok Sensation | Blog Eternal
Meet Crazyjamjam - A TikTok Sensation | Blog EternalMeet Crazyjamjam - A TikTok Sensation | Blog Eternal
Meet Crazyjamjam - A TikTok Sensation | Blog Eternal
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
 
The Evolution of Animation in Film - Mark Murphy Director
The Evolution of Animation in Film - Mark Murphy DirectorThe Evolution of Animation in Film - Mark Murphy Director
The Evolution of Animation in Film - Mark Murphy Director
 
Tom Selleck Net Worth: A Comprehensive Analysis
Tom Selleck Net Worth: A Comprehensive AnalysisTom Selleck Net Worth: A Comprehensive Analysis
Tom Selleck Net Worth: A Comprehensive Analysis
 
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdfMatt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
Matt Rife Cancels Shows Due to Health Concerns, Reschedules Tour Dates.pdf
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
 
I Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledgeI Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledge
 
Christina's Baby Shower Game June 2024.pptx
Christina's Baby Shower Game June 2024.pptxChristina's Baby Shower Game June 2024.pptx
Christina's Baby Shower Game June 2024.pptx
 
Meet Dinah Mattingly – Larry Bird’s Partner in Life and Love
Meet Dinah Mattingly – Larry Bird’s Partner in Life and LoveMeet Dinah Mattingly – Larry Bird’s Partner in Life and Love
Meet Dinah Mattingly – Larry Bird’s Partner in Life and Love
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
 
Hollywood Actress - The 250 hottest gallery
Hollywood Actress - The 250 hottest galleryHollywood Actress - The 250 hottest gallery
Hollywood Actress - The 250 hottest gallery
 
Treasure Hunt Puzzles, Treasure Hunt Puzzles online
Treasure Hunt Puzzles, Treasure Hunt Puzzles onlineTreasure Hunt Puzzles, Treasure Hunt Puzzles online
Treasure Hunt Puzzles, Treasure Hunt Puzzles online
 
Scandal! Teasers June 2024 on etv Forum.co.za
Scandal! Teasers June 2024 on etv Forum.co.zaScandal! Teasers June 2024 on etv Forum.co.za
Scandal! Teasers June 2024 on etv Forum.co.za
 

UNIT 4 python.pptx

  • 2. String • A string is a sequence of characters. • Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s. • This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used.
  • 3. How to create a string in Python? • Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
  • 4. Syntax: # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string)
  • 5. To access characters in a string • We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. • Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use floats or other types, this will result into TypeError. • Python allows negative indexing for its sequences. • The index of -1 refers to the last item, -2 to the second last item and so on.
  • 6. Slicing Operator • We can access a range of items in a string by using the slicing operator :(colon). #Accessing string characters in Python str = 'PythonProgramming' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1])
  • 7. #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2])
  • 8. Deletion updation in a string • Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name. • Example: my_string='Python' my_string[5]='a' print(my_string)
  • 9. • We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword. • Example: my_string='Python' print(my_string) del my_string[2]
  • 10. • Item deletion is not possible but a complete can be deleted with del keyword. • Example: my_string='Python' print(my_string) del my_string print(my_string)
  • 11. Reversing a Python String • With Accessing Characters from a string, we can also reverse them. We can Reverse a string by writing [::-1] and the string will be reversed. • Example: my_string='Python' #this will print simple string print(my_string) #now we will print the reversed string print(my_string[::-1])
  • 12. • We can also reverse a string by using built-in join and reversed function. • Example: my_string='Python' rev="".join(reversed(my_string)) print(rev)
  • 14. Python String Formatting 1. Escape Sequence: Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes. Example: str = "They said, "Hello what's going on?"" print(str)
  • 15. • We can use the triple quotes to accomplish this problem but Python provides the escape sequence. • The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the double quotes.
  • 16. Example # using triple quotes print('''''They said, "What's there?"''') # escaping single quotes print('They said, "What's going on?"') # escaping double quotes print("They said, "What's going on?"")
  • 17. escape character n • n it is used for providing 'new line' Let us consider an example: print("hellonpython") # will print result as follows hello python
  • 18. • it is used to represent backslash: print("hellohow are you") # will print result as follows hellohow are you • It returns one single backslash.
  • 19. • ' it is used to print a Single Quote( ' ). print("It's very powerful") # will print result as follows It's very powerful • " it is used to represent double Quote( " ) print("We can represent Strings using " ") # will print result as follows We can represent Strings using "
  • 20. • t it is used to provide a tab space print("HellotPython") # will print result as follows Hello Python
  • 21. repr() • Some times we want the escape sequence to be printed as it is without being interpreted as special. • When using with repr() or r or R, the interpreter treats the escape sequences as normal strings so interpreter prints these escape sequences as string in output. We use repr(), the built-in method to print escape characters without being interpreted as special . • We can also use both 'r'and 'R'. Internally they called repr() method.
  • 22. Example • Let us take a simple example using repr() str = "HellotPythonnPython is very interesting" print(str) # will print result as follows Hello Python Python is very interesting print(repr(str))# will print result as follows 'HellotPythonnPython is very interesting'
  • 23. • Let us consider another example using 'r' and 'R'. print(r"HellotPythonnPython is very interesting") # will print result as follows HellotPythonnPython is very interesting print(R"HellotPythonnPython is very interesting") # will print result as follows HellotPythonnPython is very interesting
  • 24. Built-in String Methods • Python provides the following built-in string methods (operations that can be performed with string objects) • The syntax to execute these methods is: stringobject.methodname()
  • 25. String lower() Method • Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it. • Example: text="Hi there" print(text.lower()) • capitalize() function is used to capitalize first letter of string. • upper() function is used to change entire string to upper case. • title() is used to change string to title case i.e. first characters of all the words of string are capitalized.
  • 26. • swapcase() is used to change lowercase characters into uppercase and vice versa. • split() is used to returns a list of words separated by space. • center(width,"fillchar") function is used to pad the string with the specified fillchar till the length is equal to width.
  • 27. Count() • count() returns the number of occurrences of substring in particular string. If the substring does not exist, it returns zero. • Example: a = "happy married life happy birthday birthday " print(a.count('happy'))
  • 28. • replace(old, new), this method replaces all old substrings with new substrings. If the old substring does not exist, no modifications are done. a = "java is simple" print(a.replace('java' ,'Python')) # will print result as follows 'Python is simple' • Here java word is replaced with Python.
  • 29. Note • The original string is left intact. Strings are immutable in Python. As you can see, the replace method doesn't change the value of the string t1 itself. It just returns a new string that can be used for other purposes
  • 30. Join() • join() returns a string concatenated with the elements of an iterable. (Here “L1” is iterable) b = '.' L1 = ["www", "codetantra", "com"] print(b.join(L1)) # will print result as follows 'www.codetantra.com' • Here '.' symbol is concatenated or joined with every item of the list.
  • 31. isupper() • isupper() function is used to check whether all characters (letters) of a string are uppercase or not. • If all characters are uppercase then returns True, otherwise False. a = 'Python is simple' print(a.isupper()) >>>False
  • 32. islower() • islower() is used to check whether all characters (letters) of a string are lowercase or not. • If all the letters of the string are lower case then it returns True otherwise False. a = "python" print(a.islower()) >>>True
  • 33. isalpha() • isalpha() is used to check whether a string consists of alphabetic characters only or not. • If the string contains only alphabets then it returns True otherwise False. a = "hello programmer" print(a.isalpha()) >>>False b = "helloprogrammer" print(a.isalpha()) >>>True • Note: Space is not considered as alphabet character, it comes in the category of special characters.
  • 34. isalnum() • isalnum() is used to check whether a string consists of alphanumeric characters. • Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. • Note: Characters those are not alphanumeric are: (space) ! # % & ? etc. Numerals 0 through 9 as well as the alphabets A - Z (uppercase and lowercase) came into the category of alphanumeric characters.
  • 35. isdigit() • isdigit() is used to check whether a string consists of digits only or not. If the string contains only digits then it returns True, otherwise False. a = "123" print(a.isdigit()) # will print result as follows True • Here the string 'a' contains only digits so it returns True.
  • 36. isspace() • isspace() checks whether a string consists of spaces only or not. If it contains only white spaces then it returns True otherwise False. a = " " print(a.isspace()) # will print the result as follows True • Here the string 'a' contains only white spaces so it returns True.
  • 37. istitle() istitle() checks whether every word of a string starts with upper case letter or not. a = "Hello Python" print(a.istitle()) # will print the result as follows True
  • 38. startswith(substring) • startswith(substring) checks whether the main string starts with given sub string. If yes it returns True, otherwise False. a = "hello python" print(a.startswith('h')) # will print result as follows True
  • 39. endswith(substring) • endswith(substring) checks whether the string ends with the substring or not. a = "hello python" print(a.endswith('n')) # will print result as follows True
  • 40. find(substring) • find(substring) returns the index of the first occurrence of the substring, if it is found, otherwise it returns -1 a = "hello python" print(a.find('py')) # will print result as follows 6
  • 41. len(a) • len(a) returns the length of the string. a = 'hello python' print(len(a)) # will print result as follows 12
  • 42. min(a) • min(a) returns the minimum character in the string a = "Hello Python" print(min(a)) # will print result as follows# min(a) prints space because space is minimum value in Hello Python. • Here it returns white space because in the given string white space is the minimum of all characters.
  • 43. max(a) • max(a) returns the maximum character in the string. print(max(a)) # will print result as follows y
  • 44. Lists
  • 45. • Python lists are one of the most versatile data types that allow us to work with multiple elements at once. • In Python, a list is created by placing elements inside square brackets [], separated by commas. # list of integers my_list = [1, 2, 3]
  • 46. • A list can have any number of items and they may be of different types (integer, float, string, etc.). # empty list my_list = [] # list with mixed data types my_list = [1, "Hello", 3.4]
  • 47. Nested List • A list can also have another list as an item. This is called a nested list. # nested list my_list = ["mouse", [8, 4, 6], ['a']]
  • 48. Access List Elements • We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4. • Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError.
  • 49. my_list = ['p', 'r', 'o', 'b', 'e'] # first item print(my_list[0]) # p # third item print(my_list[2]) # o # fifth item print(my_list[4]) # e
  • 50. • Nested lists are accessed using nested indexing. # Nested List n_list = ["Happy", [2, 0, 1, 5]] # Nested indexing print(n_list[0][1]) print(n_list[1][3])
  • 51. Negative indexing • Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. # Negative indexing in lists my_list = ['p','r','o','b','e'] # last item print(my_list[-1]) # fifth last item print(my_list[-5])
  • 52. List Slicing in Python • We can access a range of items in a list by using the slicing operator :. # List slicing in Python my_list = ['p','r','o','g','r','a','m','i','z'] # elements from index 2 to index 4 print(my_list[2:5]) # elements from index 5 to end print(my_list[5:]) # elements beginning to end print(my_list[:])
  • 53. • Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example, my_list[2: 5] returns a list with elements at index 2, 3 and 4, but not 5.
  • 54. Update List Elements • Lists are mutable, meaning their elements can be changed unlike string or tuple. • We can use the assignment operator = to change an item or a range of items.
  • 55. Example # Updating values in a list odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] print(odd)
  • 56. extend() • We can add one item to a list using the append() method or add several items using the extend() method. # Appending and Extending lists in Python odd = [1, 3, 5] odd.append(7) print(odd) odd.extend([9, 11, 13]) print(odd)
  • 57. list concatenation and repeat • We can also use + operator to combine two lists. This is also called concatenation. • The * operator repeats a list for the given number of times. # Concatenating and repeating lists odd = [1, 3, 5] print(odd + [9, 7, 5]) print(["re"] * 3)
  • 58. insert() • we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list. • # Example of list insert() method • odd = [1, 9] • odd.insert(1,3) • print(odd) • odd[2:2] = [5, 7] • print(odd)
  • 59. Delete List Elements • We can delete one or more items from a list using the Python del statement. It can even delete the list entirely.
  • 60. Example # Deleting list items my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # delete one item del my_list[2] print(my_list) # delete multiple items del my_list[1:5] print(my_list) # delete the entire list del my_list
  • 61. remove(), pop(), and clear() • We can use remove() to remove the given item or pop() to remove an item at the given index. • The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure). • And, if we have to empty the whole list, we can use the clear() method.
  • 62. Example my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list)
  • 63. # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list)
  • 64. Python List Methods • Python has many useful list methods that makes it really easy to work with lists. Here are some of the commonly used list methods. 1. append() adds an element to the end of the list 2. extend() adds all elements of a list to another list 3. insert() inserts an item at the defined index 4. remove() removes an item from the list 5. pop() returns and removes an element at the given index 6. clear() removes all items from the list
  • 65. 7. index() returns the index of the first matched item 8. count() returns the count of the number of items passed as an argument 9. sort() sort items in a list in ascending order 10. reverse() reverse the order of items in the list 11. copy() returns a shallow copy of the list
  • 66. Example # Example on Python list methods my_list = [3, 8, 1, 6, 8, 8, 4] # Add 'a' to the end my_list.append('a') # Output: [3, 8, 1, 6, 8, 8, 4, 'a'] print(my_list) # Index of first occurrence of 8 print(my_list.index(8)) # Output: 1 # Count of 8 in the list print(my_list.count(8)) # Output: 3
  • 67. List Membership Test • We can test if an item exists in a list or not, using the keyword in. my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)
  • 68. Iterating Through a List • Using a for loop we can iterate through each item in a list. for fruit in ['apple','banana','mango']: print("I like",fruit)
  • 69. list() • This function converts an iterable (tuple, string, set, dictionary) to a list • Example: print(list("abcdef")) ['a', 'b', 'c', 'd', 'e', 'f'] print(list(('a', 'b', 'c', 'd', 'e'))) ['a', 'b', 'c', 'd', 'e']
  • 70. Some other built-in list methods • all() • any() • enumerate() • len() • max() • min() • sorted() • sum()
  • 71. Tuple
  • 72. Tuple • A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
  • 73. Creating a Tuple • A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them. • A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
  • 74. Types of tuple # Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple)
  • 75. Tuple Packing • A tuple can also be created without using parentheses. This is known as tuple packing. my_tuple = 3, 4.6, "dog" print(my_tuple) # tuple unpacking is also possible a, b, c = my_tuple print(a) # 3 print(b) # 4.6 print(c) # dog
  • 76. • Creating a tuple with one element is a bit tricky. • Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
  • 77. Example my_tuple = ("hello") print(type(my_tuple)) # <class 'str'> # Creating a tuple having one element my_tuple = ("hello",) print(type(my_tuple)) # <class 'tuple'> # Parentheses is optional my_tuple = "hello", print(type(my_tuple)) # <class 'tuple'>
  • 78. Access Tuple Elements with indexes • We can use the index operator [] to access an item in a tuple, where the index starts from 0. • So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError. • The index must be an integer, so we cannot use float or other types. This will result in TypeError. • Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
  • 79. Example # Accessing tuple elements using indexing my_tuple = ('p','e','r','m','i','t') print(my_tuple[0]) # 'p' print(my_tuple[5]) # 't' # nested tuple n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested index print(n_tuple[0][3]) # 's' print(n_tuple[1][1]) # 4
  • 80. Negative Indexing • Python allows negative indexing for its sequences. • The index of -1 refers to the last item, -2 to the second last item and so on. # Negative indexing for accessing tuple elements my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple[-1]) # Output: 'p' print(my_tuple[-6])
  • 81. Slicing • We can access a range of items in a tuple by using the slicing operator colon (:). my_tuple = ('p','r','o','g','r','a','m','i','z') # elements 2nd to 4th print(my_tuple[1:4]) # elements 8th to end print(my_tuple[7:]) # elements beginning to end print(my_tuple[:])
  • 82. Changing a Tuple • Unlike lists, tuples are immutable. • This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like a list, its nested items can be changed. • We can also assign a tuple to different values (reassignment).
  • 83. Example # Changing tuple values my_tuple = (4, 2, 3, [6, 5]) # my_tuple[1] = 9 # TypeError: 'tuple' object does not support item assignment # However, item of mutable element can be changed my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5]) print(my_tuple) # Tuples can be reassigned my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple) # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
  • 84. concatenation and repeat • We can use + operator to combine two tuples. This is called concatenation. • We can also repeat the elements in a tuple for a given number of times using the * operator. • Both + and * operations result in a new tuple.
  • 85. Example # Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)
  • 86. Deleting a Tuple • we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple. • Deleting a tuple entirely, however, is possible using the keyword del.
  • 87. Example # Deleting tuples my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # del my_tuple[3] # can't delete items # TypeError: 'tuple' object doesn't support item deletion # Can delete an entire tuple del my_tuple print(my_tuple) # NameError: name 'my_tuple' is not defined
  • 88. Tuple Methods • Methods that add items or remove items are not available with tuple. • Only the following two methods are available. 1. count() 2. index()
  • 89. Example my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # Output: 2 print(my_tuple.index('l')) # Output: 3
  • 90. Tuple Membership Test • We can test if an item exists in a tuple or not, using the keyword in. # Membership test in tuple my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation print('a' in my_tuple) print('b' in my_tuple) # Not in operation print('g' not in my_tuple)
  • 91. Iterating through tuple • We can use a for loop to iterate through each item in a tuple. # Using a for loop to iterate through a tuple for name in ('John', 'Kate'): print("Hello", name)
  • 92. Advantages of Tuple over List • We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types. • Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost. • Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible. • If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
  • 93. Built-in tuple functions • enumerate(): Returns an enumerate object consisting of the index and value of all items of a tuple as pairs • Example x = (1, 2, 3, 4, 5, 6) print(tuple(enumerate(x))) >>> ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6))
  • 94. len() • This function calculates the length i.e., the number elements in the tuple • Example: x = (1, 2, 3, 4, 5, 6) print(len(x)) >>> 6
  • 95. max() & min() • max(): This function returns the item with the highest value in the tuple. print(max((1, 2, 3, 4, 5, 6))) >>> 6 • min(): This function returns the item with the lowest value in the tuple. print(min((1, 2, 3, 4, 5, 6)))
  • 96. sorted() • This function returns a sorted result of the tuple which is a list, with the original tuple unchanged. • Example: origtup = (1, 5, 3, 4, 7, 9, 1, 27) sorttup = sorted(origtup) print(sorttup) >>> [1, 1, 3, 4, 5, 7, 9, 27] print(origtup) >>> (1, 5, 3, 4, 7, 9, 1, 27)
  • 97. sum() • This function returns the sum of all elements in the tuple. • This function works only on numeric values in the tuple and will error out if the tuple contains a mix of string and numeric values. • Example: print(sum((1, 5, 3, 4, 7, 9, 1, 27))) 57 print(sum((1, 3, 5, 'a', 'b', 4, 6, 7))) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • 98. tuple() • This function converts an iterable (list, string, set, dictionary) to a tuple • Example: x = list("abcdef") print(x) ['a', 'b', 'c', 'd', 'e', 'f'] print(tuple(x)) ('a', 'b', 'c', 'd', 'e', 'f')
  • 100. Dictionary • Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike other data types which hold only a single value as an element. • Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it more optimized. • we can create a dictionary using the built-in dict() function as well.
  • 101. Creating Python Dictionary • A dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable. • Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
  • 102. Example # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')])
  • 103. Accessing Elements from Dictionary • While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method. • If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.
  • 104. Example # get vs [] for retrieving elements my_dict = {'name': 'Jack', 'age': 26} print(my_dict['name']) # Output: Jack print(my_dict.get('age')) # Output: 26
  • 105. Updating dictionary elements • Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator. • If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.
  • 106. Example # Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 print(my_dict) #Output: {'age': 27, 'name': 'Jack'} # add item my_dict['address'] = 'Downtown' print(my_dict) # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
  • 107. Removing elements from Dictionary • We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value. • The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method. • We can also use the del keyword to remove individual items or the entire dictionary itself.
  • 108. Example squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value print(squares.pop(4)) # Output: 16 print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25} # remove an arbitrary item, return (key,value) print(squares.popitem()) # Output: (5, 25) print(squares) # Output: {1: 1, 2: 4, 3: 9}
  • 109. Example (Continues..) # remove all items squares.clear() print(squares) # Output: {} # delete the dictionary itself del squares print(squares) # Throws Error
  • 110. Python Dictionary Methods • clear(): Removes all items from the dictionary. • copy(): Returns a shallow copy of the dictionary. • fromkeys(sequence,value): Returns a new dictionary with keys from seq and value equal to v (defaults to None). • get(key,default=None): Returns the value of the key. If the key does not exist, returns d (defaults to None). • items(): Return a new object of the dictionary's items in (key, value) format. • keys(): Returns a new object of the dictionary's keys.
  • 111. • pop(key): Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. • popitem(): Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. • setdefault(key,default=None): Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). • update(dict2): Updates the dictionary with the key/value pairs from other, overwriting existing keys. • values(): Returns a new object of the dictionary's values
  • 112. Example marks = {}.fromkeys(['Math', 'English', 'Science'], 0) print(marks) # >>> {'English': 0, 'Math': 0, 'Science': 0} for item in marks.items(): print(item) #>>> ('Math', 0) #>>> ('English', 0) #>>> ('Science', 0) print(list(sorted(marks.keys()))) #>>> ['English', 'Math', 'Science']
  • 113. Dictionary Membership Test • We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values. • Example: squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} print(1 in squares) # Output: True
  • 114. Iterating Through a Dictionary • We can iterate through each key in a dictionary using a for loop. # Iterating through a Dictionary squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i])
  • 115. Dictionary Built-in Functions • all(): Return True if all keys of the dictionary are True (or if the dictionary is empty). • any(): Return True if any key of the dictionary is true. If the dictionary is empty, return False. • len(): Return the length (the number of items) in the dictionary. • cmp(): Compares items of two dictionaries. (Not available in Python 3) • sorted(): Return a new sorted list of keys in the dictionary.
  • 116. Example squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: [0, 1, 3, 5, 7, 9] print(sorted(squares))