UNIT-4
String,list,tuple,Dictionary
STRINGS
String is sequence of characters are
surrounded by either single quotation marks,
or double quotation marks.
String is immutable
'hello' is the same as "hello".
The element is accessed by positive or
negative indexing.
STRING LENGTH
To get the length of a string, use
the len() function.
Example
The len() function returns the length of a
string:
a = "Hello, World!"
print(len(a))
OUTPUT:12
FIVE OPERATIONS CAN BE
PERFORMED ON STRING
Indexing
slicing
Concatenation
Repetition
membership
OPERATION 1: INDEXING
A=‘hello’
#print second element from string A from
beginning
print(A[1])
Output: e
print second last element from string A from
ending
Print(A[-2])
OUTPUT: l
OPERATION 2: SLICING
Extract a part of a string using a concept
called Slicing.
It is used to extract a specific part of a string
using a startIndex and an endIndex.
The syntax for using the slice operation on a
string is:
[startIndex : endIndex : step]
EXAMPLE:
Example l4 = [1,4,6,22,44,12,55,66]
Slicing expression
l4 [1:4] Output: [4,6,22]
L4[3:-3] Output: [22,44]
L4[3:] Output:[22,44,12,55,66]
L4[:4] Output: [1,4,6,22]
EXAMPLES ON SLICING OPERATIONS
REMOVE THE FIRST AND LAST
CHARACTER FROM STRING
a = ‘python’
Print(a[1:-1])
Output: ytho
SWAP THE FIRST AND LAST
CHARACTER FROM STRING
A=‘active’
A[0:1] #a
A[-1] #e
A[1:-1:1] #ctiv
Concatenate: A[-1]+A[1:-1:1]+A[0:1]
OUTPUT:ectiva
TYPE3: CONCATENATION
Combining two string into one string.
A=python
B=programming
Ques: #DISPLAY ping from string A and b
Print(a[0:]+b[-3:]
TYPE4: MEMBERSHIP
OPERATOR
Membership Operators in and not in are used
to check whether a certain element exits
within a sequence such as string, list, tuple
or set.
The in operator returns True if the specified
element is found in the sequence.
Otherwise, it returns False
The not in operator returns True if the
specified element is not found in the
sequence. Otherwise, it returns False
EXAMPLE:
TYPE 5: REPETITION
use ( * ) operator to repeat a string several
times.
a = "Mouse“
print(3 * a) # Output: MouseMouseMouse
print(a * 3) # Output: MouseMouseMouse
PROGRAM TO REMOVE
CHARACTER BASED ON INTEGER
str=input("str: ")
num=int(input("num: "))
c=0
if(len(str)>num):
st=str[0:num]+str[num+1:]
elif(len(str)==num):
st=str[0:num]
elif(len(str)<num):
c=1
if(c==0):
print("output:",st)
else:
print("num should be positive, less than the length of str")
BUILT-IN STRING METHODS
ESCAPE OPERATOR
Ques1:Remove the specific element from
string ‘Allahabad’ based on integer value
entered by user.