Session-7 (String in Python)
Session-7 (String in Python)
Python Data
Python is a dynamically typed language
Types hence we need not define the type of
the variable while declaring it.
String
In python, we can use single,
double, or triple quotes to define a
string.
Example
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
Output:
• Another way of accessing the H
• String Traversal Using for Loop: elements of the string is using e
range() and len() functions: l
>>> str1 = 'Hello World!' l
>>> for ch in str1: >>> str1 = 'Hello World!' o
Repetition
STRING
OPERATIONS
Membership
Slicing
Note: str1 and str2 still remains the same after the use of
concatenation operator.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
• The * operator repeats a string for the given
number of times.
• The repetition operator requires the first
operand to be a string and the second operand
to be an integer only.
Replication/ • Eg.-
Repetition >>> str1 = 'Hello'
>>> str1 * 3
'HelloHello'Hello'
• Note: str1 still remains the same after the use of
repetition operator.
by space.
• Eg.-
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
What will be the output of the following code segment:
Consider the following string mySubject:
mySubject = "Computer Science"
What will be the output of the following string operations :
i. print(mySubject[0:len(mySubject)])
ii. print(mySubject[-7:-1])
iii. print(mySubject[::2])
iv. print(mySubject[len(mySubject)-1])
v. print(2*mySubject)
vi. print(mySubject[::-2])
vii. print(mySubject[:3] + mySubject[3:])
viii. print(mySubject.swapcase())
ix. print(mySubject.startswith('Comp'))
x. print(mySubject.isalpha())
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
What will be the output of the following code segment:
Consider the following string myAddress:
myAddress = "WZ-1,New Ganga Nagar,New Delhi"
What will be the output of following string operations :
i. print(myAddress.lower())
ii. print(myAddress.upper())
iii. print(myAddress.count('New'))
iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New'))
vi. print(myAddress.split(','))
vii. print(myAddress.split(' '))
viii. print(myAddress.replace('New','Old'))
ix. print(myAddress.partition(','))
x. print(myAddress.index('Agra'))
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
PROGRAMMING PROBLEMS
• Write a program that takes a sentence as an input
where each word in the sentence is separated by a
space. The program should replace each blank with
a hyphen and then return the modified sentence.
• Write a program which replaces all vowels in the
inputted string with '*'.
• Write a program to check if a string is a palindrome
or not. (A string is called palindrome if it reads same
backwards as forward. For example, MADAM is a
palindrome.)