DOC-20250209-WA0003.
DOC-20250209-WA0003.
STRINGS:
● Python strings are characters enclosed in quotes of any — single quotation
marks, double quotation and triple quotation marks.
● An empty string is a string that has 0 characters (i.e., it is just a pair of
quotation marks).
● Python strings are immutable.
● Each character has a unique Position-id/index.
● The indexes of a string begin from 0 to (length — l) in forward direction and
-1, -2, -3, .. -length in backward direction.
● We can primarily write a string in these three ways
TRAVERSING A STRING:
● Traversing refers to iterating through the elements of a string one
character at a time.
● The individual characters of a string are accessible through the unique
index of each character.
● Using the indexes, you can traverse a string character by character.
● Traversing refers to iterating through the elements of a string one
character at a time.
● To traverse through a string you can write a loop like :
name = “superb”
for ch in name :
print( ch , ‘-’, end =” “ )
PROBLEM: Program to read a string and display it in reverse order - display one
character per line .Do not create a reverse string. just display in reverse order.
SOLUTION: string1 = input( "Enter a string : " )
print ("The", string1, "in reverse order is:")
length = len(string1)
for a in range (-1, (- length—1), —1) :
print (string1[a] )
STRING OPERATORS:
● We have many operators that can be used to manipulate strings in multiple
ways. They are basic + and *, membership operators in and not in and
comparison (all relational operators) for strings.
Basic Operators:
● Two basic operators of strings are : + and *. These operators are used as
arithmetic operators for addition and multiplication respectively.
● But when used With strings, + operator performs concatenation rather
than addition and * operator performs replication rather than
multiplication.
● As we know that strings are immutable i.e., un-modifiable, thus every time
someone performs something on a string that tries to change it, Python will
internally create a new string rather than modifying the old string in place.
NOTE: The + operator has to have both operands of the same type either of
number type (for addition) or of string types (for multiplication). It cannot work
with one operand as string and one as a number.
Membership Operators
● There are two membership operators for strings (in fact for all sequence
types). These are in and not in.
● in : Returns True if a character or a substring exists in the given string ;
False otherwise
● not in : Returns True if a character or a substring does not exist in the
given string; False otherwise.
● Both membership operators (when used with strings), require that both
operands used with them are of string type, i.e.,
<string> in <string>
<string> not in <string>
e.g.,
"12" in "xyz"
"12" not in "xyz"
Comparison Operators
● python's standard comparison operators i.e., all relational operators (<, <=,
>, >=, ==, !=) apply to strings also.
● The comparisons using these are on the standard character-by-character
comparison rules for unicode (i.e., dictionary order).
e.g.
“a” == “a” will give True
“Abc” == “abc” will give False
“A” != “a” will give True
“Abc” ==”ABC” will give False
STRING SLICES
● The term 'string slice' refers to a part of the string, where strings are sliced
using a range of indices.
● That is, for a string say name, if we give name[ n : m ] where n and m are
integers and legal indices, Python will return a slice of the string by
returning the characters falling between indices n and m - starting at n,
n+1, n +2 till m -1 .
● Suppose we have a string namely ‘word’ storing a string 'amazing' i.e.,
● In a string slice, you give the slicing range in the form [<begin-index> :
<last>].
● If, however, one can skip either of the begin-index or last, Python will
consider the limits of the string i.e., for missing begin-index, it will consider
'0' (the first index) and for missing last value, it will consider length of the
string.
● Consider following example to understand this :
x = txt.capitalize( )
print (x)
Output: Python is fun!
print(x)
Output: 1
3. The endswith() method returns True if the string ends with the specified
value, otherwise False.
Syntax: string.endswith(value, start, end)
txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)
Output: True
4. The find() method finds the first occurrence of the specified value.The
find() method returns -1 if the value is not found.The find() method is
almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found.
E.g.
x = txt.find("e")
print(x)
Output: 1
E.g.
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
Output: three three was a race horse, two two was three too."
6. The split() method splits a string into a list. One can specify the
separator, default separator is any whitespace.
x = txt.split(", ")
print(x)
7. The join() method takes all items in an iterable and joins them into one
string. A string must be specified as the separator.
Syntax: string.join(iterable)
E.g.
Output: nameTESTcountry
8. The isalpha() method returns True if all the characters are alphabet
letters (a-z). Example of characters that are not alphabet letters:
(space)!#%&? etc.
Syntax: string.isalpha()
E.g.
txt = "Company10"
x = txt.isalpha()
print(x)
Output: False
Syntax: string.isalnum()
E.g.
x = txt.isalnum()
print(x)
Output: False
LISTS:
● The Python lists are containers that are used to store a list of values
of any type.
● Unlike other variables Python lists are mutable i.e., you can change
the elements of a list in place ; Python will not create a fresh list when
you make changes to an element of a list
● List is a type of sequence like strings and tuples but it differs from
them in the way that lists are mutable but strings and tuples are
immutable.
Creating Lists
● To create a list, put a number of expressions in square brackets.
● That is, use square brackets to indicate the start and end of the list,
and separate the items by commas. (as shown above)
NESTED LIST:
● A list has an element in it, which itself is a list.
● Such a list is called a nested list, e.g.
L1 =[3, 4, [5,6], 7]
● L1 is a nested list with four elements : 3, 4, [5, 6] and 7, L1[2] element is
a list [5, 6]. Length of L1 is 4 as it counts [5, 6] as one element.
Traversing a List:
● Traversal of a sequence means accessing and processing each
element of it.
● Thus traversing a list also means the same and same is the tool for it,
i.e., the Python loops.
● That is why sometimes we call a traversal as looping over a
sequence. e.g.
1. Joining Lists
Joining two lists is very easy just like you perform addition. The
concatenation operator +, when used with two lists, joins two lists. Consider
the example given:
>>>list2 = [6, 7, 8]
>>>list1 +list2
[1, 2, 3, 4, 5, 6, 7, 8]
NOTES: The* operator when used with lists requires that both the
operands must of list types. We cannot add a number or any other value to
a list.
>>>list1*2
[1, 2, 3, 4, 1, 2, 3, 4]
NOTE: pop method is important when we want to store the element being
deleted for later use
x = fruits.index(32)
print(x)
Output: 3
points = (1, 4, 5, 9)
fruits.extend(points)
fruits.insert(1, "orange")
x = fruits.pop(1)
Output:banana
E.g.
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
fruits.clear()
Output: []
x = fruits.count("cherry")
Output: 1
10. The sort method: The sort() method sorts the list
ascending by default.You can also make a function to decide
the sorting criteria(s).
● The Python tuples are sequences that are used to store a tuple
of values of any type.
● Python tuples are immutable i.e. we cannot change the
elements of a tuple in place ; Python will create a fresh tuple
when you make changes to an element of a tuple.
● Tuple is a type of sequence like strings and lists but it differs
from them in the way that lists are mutable but strings and
tuples are immutable.
Creating Tuples:
# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: apple
print(my_tuple[2]) # Output: 3.14
Tuple Operations:
1. Concatenation:
● Tuples can be concatenated using the + operator.
tuple1 = (1, 2)
tuple2 = (3, 4)
2. Repetition:
my_tuple = ('hello',) * 3
3. Slicing:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])
Output: (2, 3, 4)
This is used to check whether the given tuples are the same or not. If both
are same, it will return ‘zero’, otherwise return 1 or -1. If the first tuple is big,
then it will return 1, otherwise return -1.
Syntax:
returns 0 or 1 or -1
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300)
>>> T3=(10,20,30)
>>> cmp(T1,T2)
-1
>>> cmp(T1,T3)
>>> cmp(T2,T1)
len( )
Syntax:
Example
>>> T2=(100,200,300,400,500)
>>> len(T2)
Output:
max( ):
Syntax:
>>> T=(100,200,300,400,500)
>>> max(T)
Output:
500
min( ):
Syntax:
Example
>>> T=(100,200,300,400,500)
>>> min(T)
Output:
100
Tuple Methods:
my_tuple = (1, 2, 3, 2, 2, 5)
print(my_tuple.count(2))
Output: 3
● index(): Searches the tuple for a specified value and returns the
position of where it was found.
my_tuple = (1, 2, 3, 2, 2, 5)
print(my_tuple.index(5))
Output: 5
Dictionary:
Syntax:
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
>>> D=dict()
>>> print D
{} #output
● {} represents an empty string.
● To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary
values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
Traversing a dictionary:
Example :
for i in H:
Output:
Syntax:
Example
>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}
>>> a["thu"]="thursday"
>>> print a
Output :
Merging dictionaries:
● Two dictionaries can be merged into one by using update ( ) method.
● It merges the keys and values of one dictionary into another and
overwrites values of the same key.
Syntax:
Dic_name1.update (dic_name2)
Using this dic_name2 is added with Dic_name1.
Example :
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
Removing an item from dictionary:
● We can remove items from the existing dictionary by using del
key word.
Syntax:
del dicname[key]
Example
>>>A={"mon":"monday","tue":"tuesday","wed":"wednesday","thu":"thursday"}
>>> del A["tue"]
>>> print A
output:
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday'}
2. len( )
● This method returns a number of key-value pairs in the given
dictionary.
Example
>>> H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
>>> len(H)
Output:
4
3. clear ( ):
● It removes all items from the particular dictionary.
Example :
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.get('name')) # Output: Alice
print(my_dict.get('address', 'N/A')) # Output: N/A
Module:
● A module is a file containing Python definitions (i.e. functions) and
statements.
● Standard library of Python is extended as module(s) to a
programmer.
● Functions from the module can be used within the code of a
program.
● To use these modules in the program, a programmer needs to
import the module.
● Once you import a module, we can use any of its functions or
variables in our code.
● Import is the simplest and most common way to use modules in our
code.
● Its syntax is:
import modulename1 [,modulename2, ---------]
Example
>>> import math
Example
>>> value= math.sqrt (25) # dot notation
Built in Function:
● Built in functions are the function(s) that are built into Python and
can be accessed by a programmer.
● These are always available and for using them, we don’t have to
import any module.
● Python has a small set of built-in functions as most of the functions
have been partitioned to modules. This was done to keep the core
language precise.
● For example range( ), round( ), id( ), len( ), type( ) etc.
Example
def check (num):
if (num%2==0):
print (True)
else:
print (False)
result = check (29)
False
print (result)
None
Defining Functions:
● It is possible to provide parameters of function with some default
value.
● In case the user does not want to provide values (argument) for all of
them at the time of calling, we can provide default argument values.
Example:
def greet (message, times=1):
print message * times
>>> greet (‘Welcome’) # calling function with one argument value
>>> greet (‘Hello’, 2) # calling function with both the argument values.
Output
Welcome
HelloHello
Note:
● The default value assigned to the parameter should be a constant
only.
● Only those parameters which are at the end of the list can be given a
default value.
● We cannot have a parameter on the left with default argument value,
without assigning default values to parameters lying on its right side.
● The default value is evaluated only once, at the time of function
definition.
Example:
def fun(a, b=1, c=5):
print (‘a is , a, ‘b is ‘, b, ‘c is ‘, c)
Note: The function named fun ( ) has three parameters out of which the first
one is without default value and other two have default values. So any call
to the function should have at least one argument.