0% found this document useful (0 votes)
48 views

Class 11 Strings (Complete)

The document discusses strings in Python. It defines what a string is, how they can be created and assigned, various operations that can be performed on strings like concatenation, replication, comparison, membership testing, and slicing strings to extract substrings.

Uploaded by

Vansh Singhania
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Class 11 Strings (Complete)

The document discusses strings in Python. It defines what a string is, how they can be created and assigned, various operations that can be performed on strings like concatenation, replication, comparison, membership testing, and slicing strings to extract substrings.

Uploaded by

Vansh Singhania
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Computational Thinking

© CS-DEPT DPS MATHURA ROAD


and Programming - 1
Python - Strings

XI
Definition
A Python string is a sequence of characters stored in contiguous memory
locations.It is an immutable data type.

© CS-DEPT DPS MATHURA ROAD


String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be
created by enclosing one or more characters in single, double or triple quote.
Each character can be individually accessed using its index. These characters can be
accessed using either forward indexing or backward indexing.
You can access any character as <stringname>[index].
The index can be a forward index or a backward index.
➢ 0, 1, 2,.... In the forward direction
➢ -1, -2, -3….. In the backward direction

2
XI
Indexing

© CS-DEPT DPS MATHURA ROAD


Forward Indexing

0 1 2 3 4 5

string P Y T H O N
-6 -5 -4 -3 -2 -1

Backward Indexing

3
XI
Traversing a string
Individual character of a string can be accessed using the method of indexing. Each

© CS-DEPT DPS MATHURA ROAD


character of a string is referred by an integer which is known as Index or subscript.
The index or subscript starts from 0 and must be an integer.

Traversing a string means accessing all the elements of the string one after
another by using the subscript or index where the index or subscript is given
within [ ] with the stringname.

The index used to access character of a string can be positive or negative integers.

● Positive subscript helps in accessing the string from the beginning


● Negative subscript helps in accessing the string from end
● Subscript 0 or –n (where n is the length of the string) displays the first
character, 1 or –(n-1) displays the second character and so on.
4
XI
Traversing a string

© CS-DEPT DPS MATHURA ROAD


0 1 2 3 4 5 6 7
String (str) C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1

print(str[0]) Displays first character from


beginning
print(str[7] ) Displays last character
print(str[-8] ) Displays first character from
begining
print(str[-4] ) Displays 4th character from
the end 5
XI
Assigning a string
String is a collection of ASCII/Unicode characters. Its content can represented

© CS-DEPT DPS MATHURA ROAD


within a set of single or double quotes.
Name='Amar Shah'
City="Hyderabad"
Place="King's Palace"
Title='The Dream of "Doll" uncovered'
print(Name,"Lived in the", Place,"at", City)
print("His best book was entitled as",Title)

Output
Amar Shah Lived in the King's Palace at Hyderabad
His best book was entitled as The Dream of "Doll" uncovered
6
XI
Assigning a string
String can also be created using Escape sequence characters as a part of the string.

© CS-DEPT DPS MATHURA ROAD


The following example shows the use of \n and \t escape sequence characters for tab
and new line
message = "Programming Language:\t Python\n Developed
by Guido Van Rossum"
print(message)

Output
Programming Language: Python
Developed by Guido Van Rossum

7
XI
Assigning a string
Python does not support a character data type, these are treated as strings of length

© CS-DEPT DPS MATHURA ROAD


one.

For example : >>grade="A"


>>ch="*"

A string without any character inside is known as Empty String. When an Empty string
is displayed using print(), a blank space gets displayed.
>>ch=""
>>print(ch)
''
8
XI
Operations on Strings

© CS-DEPT DPS MATHURA ROAD


OPERATIONS

String
Concatenation Replication Comparison Membership
Slicing

9
XI
Concatenation
The + operator takes two strings as operands and results a new string by joining the
two operand strings.

© CS-DEPT DPS MATHURA ROAD


Syntax : string literal 1/object 1+string literal 2/object 2
Example :
>>a="Computer"
>>b='Science'
>>print(a+b)

Output
ComputerScience

10
XI
Replication
The * operator as a replication operator needs two operand i.e a string and an

© CS-DEPT DPS MATHURA ROAD


integer. Python replicates the string operand the given number of times.

Syntax : string literal /object * integer data item

Example : >> a="Computer"


>>print(a*3)

Output
ComputerComputerComputer

11
XI
Comparison
All relational and comparison operators (==, >, <, <=, >=, !=) can be used to
compare two strings .

© CS-DEPT DPS MATHURA ROAD


The comparison will be done on the basis of ASCII value of the character. Python
compares first element of each string. If they are the same ,it goes on to the next
element and so on .

Example : If there are three strings ,


s1=”science”
s2=”science”
s3=”Science”

12
XI
Common Characters and Ordinal Values
CHARACTERS ORDINAL VALUES

© CS-DEPT DPS MATHURA ROAD


0 to 9 48 to 57
“A” to “Z” 65 to 90
“a” to “z” 97 to 122

Python provides a built in function ord() that takes in a single character and
returns the ordinal value.
Syntax : ord(<single-character>) ch=’a’
ord(ch)
>>ord("a")
97
13
XI
Membership
The operators in and not in are used to check whether a string exists in the given

© CS-DEPT DPS MATHURA ROAD


string or not. The operands of in and not in operators are strings.

Syntax : <string1> in <string2>


<string1> not in <string2>
Example :

14
XI
String Slicing
String slicing refers to the part of the string or a subset of a string.This subset of a

© CS-DEPT DPS MATHURA ROAD


string (the substring) is termed as slice. To extract the slice two indexes are given
in square bracket separated by a colon (:).

Syntax : string_name [start : end : step]


where start, end and step are integers
start represents the starting index of string
end denotes the end index of string which is not inclusive
step denotes the distance between the elements to be sliced

Example : string1[2:5]

C o m p u t e r
0 1 2 3 4 5 6 7
15
XI
String Slicing

© CS-DEPT DPS MATHURA ROAD


Python will return a slice of the substring by returning the character
falling between the start and end-1 position

However , while slicing string, start, end and step can be omitted.

● When start position is omitted, Python considers it to be 0.


● When end position is omitted, Python will extract the string
starting from start position till the end of the string.
● When both are omitted, Python will extract the entire string.
● When step is omitted, Python assigns it as 1
● When start value >stop value, step should be negative

16
XI
String Slicing
The start and end values can be –ve integers in which Python counts from

© CS-DEPT DPS MATHURA ROAD


the right hand side.

Example :

>>> str= "Computer Science"


>>> print(str[-3:]) nce
>>> print(str[:-3]) Computer Scie
>>>print(str[-6:-1]) cienc
>>> print(str[-10:-2:2]) e ce
>>> print(str[-2:-15:-2]) cec eum #when start>stop,
step should be -ve
>>> str1=str[-1:-17:-1] 'ecneicS retupmoC'
#Reverse of str stored in str1
17
XI
String Slicing
Index out of bound causes errors with strings but slicing a string
outside the bounds does not cause error

© CS-DEPT DPS MATHURA ROAD


Example: h e l l o
0 1 2 3 4
s=”hello” -5 -4 -3 -2 -1
print(s[5]) -> will cause error as 5 is invalid
index-out-of-bound
But, print(s[4:8]) -> valid
print(s[5:10]) -> valid

18
XI
String Slicing
0 1 2 3 4 5 6 7

© CS-DEPT DPS MATHURA ROAD


String (str) C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1

Output
print(str[3:7] ) pute
print(str[4:] ) uter
print(str[:6] ) Comput
print(str[1::2] ) optr
print(str[-3:]) ter
19
XI
Answer the following :
String (str)

© CS-DEPT DPS MATHURA ROAD


C o m p u t e r S c i e n c e
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

>>> str= "Computer Science"


>>> print( str[3:7] )
>>> print( str[4:] )
>>> print( str[0:] )
>>> print( str[:6] )
>>> print( str[:7] )
>>> print( str[1:10:2] )
>>> print( str[4: :2] )
>>> print( str[:10:2] )
>>> print( str[10:2:-1] )

20
XI
Solution:

© CS-DEPT DPS MATHURA ROAD


>>> str= "Computer Science"
>>> print( str[3:7] ) pute
>>> print( str[4:] ) uter Science
>>> print( str[0:] ) Computer Science
>>> print( str[:6] ) Comput
>>> print( str[:7] ) Compute
>>> print( str[1:10:2] ) optrS
>>> print( str[4: :2] ) ue cec ( #end value is omitted )
>>> print( str[:10:2] ) Cmue
>>> print( str[10:2:-1] ) cS retup (# when start>stop, step
has to be negative)

21
XI
String Functions & Methods
len()

© CS-DEPT DPS MATHURA ROAD


capitalize()

String Functions and Methods


title()

lower()

upper()

isupper()

islower()

isdigit()
22
XI
String Functions & Methods
isspace()

© CS-DEPT DPS MATHURA ROAD


String Functions and Methods
isalpha()

rstrip()

lstrip()

partition()

replace()

split()
23
XI
String Functions and Methods
1. len()

© CS-DEPT DPS MATHURA ROAD


Returns the length of the string or the number of characters in the string

Syntax : len(stringname)

Example

>>> str="i love india"


>>> print(len(str))
12

24
XI
String Functions and Methods
2. capitalize()

© CS-DEPT DPS MATHURA ROAD


Returns the copy of the string with the first character capitalised.

Syntax : stringname.capitalize()

Example
>>> str="hello"
>>>print(str.capitalize())
Hello

25
XI
String Functions and Methods
3. title()

© CS-DEPT DPS MATHURA ROAD


Returns a string which has first letter in each word is uppercase and all
remaining letters are lowercase.
Syntax : stringname.title()

Example
>>> str="hello how are you"
>>>print(str.title())
Hello How Are You

26
XI
String Functions and Methods
4. upper()

© CS-DEPT DPS MATHURA ROAD


Returns an exact copy of the string with all the letters in uppercase

Syntax : stringname.upper()

Example
>>> str="learn python"
>>>print(str.upper())
LEARN PYTHON

27
XI
String Functions and Methods
5. lower()

© CS-DEPT DPS MATHURA ROAD


Returns an exact copy of the string with all the letters in lowercase

Syntax : stringname.lower()

Example
>>> str="PYTHON"
>>>print(str.lower())
python

28
XI
String Functions and Methods
6. isupper()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are uppercase letters.

Syntax : stringname.isupper()

Example
>>>word='ABC'
>>>print(word.isupper())
True

29
XI
String Functions and Methods
7. islower()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are lowercase letters.

Syntax : stringname.islower()

Example
>>>word='xyz'
>>>print(word.islower())
True

30
XI
String Functions and Methods
8. isdigit()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are digits.

Syntax : stringname.isdigit()

Example
>>>word='123'
>>>print(word.isdigit())
True

31
XI
String Functions and Methods
9. isalpha()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are alphabets.

Syntax : stringname.isalpha()

Example
>>>word='alpha123'
>>>print(word.isalpha())
False
>>>word='abcdef'
>>>print(word.isalpha())
True
32
XI
String Functions and Methods
10. isalnum()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are alphabets or digits.

Syntax : stringname.isalnum()

Example
>>>word='alpha123'
>>>print(word.isalnum())
True
>>>word='abc123'
>>>print(word.isalnum())
True
33
XI
String Functions and Methods
11. isspace()

© CS-DEPT DPS MATHURA ROAD


Returns True if all the characters in the string are white space.

Syntax : stringname.isspace()

Example >>>word='alpha123'
>>>print(word.isspace())
False
>>>word=' '
>>>print(word.isspace())
True

34
XI
String Functions and Methods
12. split()

© CS-DEPT DPS MATHURA ROAD


Returns a list of strings after breaking the given string by the specified
separator.

Syntax : stringname.split([separator,maxsplit])

Example
>>>word='DPS Mathura Road Delhi'
>>>print(word.split())
['DPS', 'Mathura', 'Road', 'Delhi']

35
XI
String Functions and Methods
>>>word='DPS,Mathura,Road,Delhi'

© CS-DEPT DPS MATHURA ROAD


Example
>>>print(word.split(',',0))

['DPS,Mathura,Road,Delhi']

>>>word='DPS,Mathura,Road,Delhi'
Example
>>>print(word.split(',',2)) Max splits

['DPS', 'Mathura', 'Road,Delhi']

36
XI
Split function

© CS-DEPT DPS MATHURA ROAD


T = "LEARN PYTHON"

#Splits at space
["LEARN", "PYTHON"]
print(T.split())

print(T.split('R'))
['LEA', 'N PYTHON']

print(T.split('O')) ['LEARN PYTH','N']

37
XI
String Functions and Methods
13. strip()

© CS-DEPT DPS MATHURA ROAD


Returns a copy of string after removing leading or trailing characters passed as
argument. If no argument is provided, whitespaces are taken by default.

Syntax : stringname.strip(character)

Example >>>word='Python Programming'


>>>print(word.strip('g'))
'Python Programmin'

>>>word=' Python Programming '


>>>print(word.strip())
'Python Programming'
38
XI
String Functions and Methods
14. lstrip()

© CS-DEPT DPS MATHURA ROAD


Returns a copy of string after removing leading characters passed as argument. If no
argument is provided, whitespaces are taken by default.

Syntax : stringname.lstrip(character)

Example >>>word='Python Programming'


>>>print(word.lstrip('P'))
'ython Programming'

39
XI
String Functions and Methods
15. rstrip()

© CS-DEPT DPS MATHURA ROAD


Returns a copy of string after removing trailing characters passed as argument. If no
argument is provided, whitespaces are taken by default.

Syntax : stringname.rstrip(character)

Example >>>word='Python Programming'


>>>print(word.rstrip('g'))
'Python Programmin'

40
XI
String Functions and Methods
16. partition()

© CS-DEPT DPS MATHURA ROAD


Returns a tuple of strings after splitting the string at first occurrence of
Argument. Returns a tuple of length 3.

Syntax : stringname.partition(character)

Example >>>word='Python is interesting'


>>>print(word.partition('is'))
('Python','is','interesting')

41
XI
partition ()

© CS-DEPT DPS MATHURA ROAD


p=”peace on earth” ('peace', ' on ', 'earth')
print(p.partition(' on '))
('peace on earth', '', '')
print(p.partition('moon '))
('', 'peace ', 'on earth')
print(p.partition('peace '))
('p', 'e', 'ace on earth')
print(p.partition('e'))
print(p.partition('h')) ('peace on eart', 'h', '')

42
XI
String Functions and Methods
17. find()

© CS-DEPT DPS MATHURA ROAD


Returns the lowest index in the string where the substring is found or within the slice range (if
specified. If not specified, the range is taken as start - 0th index and end - last index. Returns
-1 if sub is not found.

Syntax : String.find (substring[, start[, end]])

Example >>>word=”We learn C++"


>>>print(word.find("learn")
3

>>>word=”We learn C++"


>>>print(word.find("yearn")
-1
43
XI
String Functions and Methods
18. count()

© CS-DEPT DPS MATHURA ROAD


Returns the number of occurrences of a substring in the given string. Returns 0 if not found.

Syntax : String.count (substring [, start[, end]])

Example >>>s = 'I like programming and animation both'


>>>print(s.count("like")
1

44
XI
String Functions and Methods
19. replace()

© CS-DEPT DPS MATHURA ROAD


Returns copy of string which has replaced all old substring with new substring.

Syntax : str.replace(oldsubstring,new substring)

Example >>>word='We learn C++'


>>>print(word.replace("C++","PYTHON"))

We Learn PYTHON

45
XI
Question 1
Program to traverse a string inputted by user and display it.

© CS-DEPT DPS MATHURA ROAD


str1=input("Enter the string :") Output :
for i in str1:
print(i) Enter the string : PYTHON
P
Y
str1=input("Enter the string :") T
for i in range(len(str1)): H
print(str1[i]) O
N

46
XI
Question 2
Program to input a string and display the string in reverse order.

© CS-DEPT DPS MATHURA ROAD


str1=input("Enter the string :") Output :
l=len(str1)
for i in range(l-1,-1,-1): Enter the string : PYTHON
print(str1[i]) N
O
H
str1=input("Enter the string :") T
str2=str1[::-1] Y
print(str2) P

47
XI
Question 3
Program to input a string and then print the number of uppercase letters, lowercase

© CS-DEPT DPS MATHURA ROAD


letters, alphabets and digits.
str= input("Enter string : ") Output :
cntalpha=0
cntdigit=0
cntupper=0
Enter string:EAT 123 code
cntlower=0 No of alphabets : 6
for ch in str:
if ch.islower() :
No of digits : 3
cntlower+=1 No of uppercase characters: 3
elif ch.isupper() :
cntupper+=1
No of lowercase characters : 4
elif ch.isdigit() :
cntdigit+=1
if ch.isalpha() :
cntalpha+=1
print("No of alphabets : ",cntalpha)
print("No of digits : " ,cntdigit)
print("No of uppercase characters : ",cntupper)
print("No of lowercase characters : ",cntlower) 48
XI
Question 4
Write a program that reads a string and creates a new string by capitalising

© CS-DEPT DPS MATHURA ROAD


every alternate letter in the string.
str = input("enter a string ") Output :
length = len(str)
newstr='' Enter string:apple
for i in range(0,length): ApPlE
if i%2==0:
newstr=newstr+str[i].upper()
else:
newstr+=str[i]
print(newstr)

49
XI
Question 5
Program to input a string and then check if it a palindrome or not.

© CS-DEPT DPS MATHURA ROAD


str = input("Enter a string :") Output :
length = len(str)
valid = True Enter string:KANAK
for i in range(length//2): KANAK is a palindrome
if str[i] != str[length - i - 1]:
valid = False
break
if valid:
print(str," is a palindrome")
else:
print(str," is not a palindrome")

50
XI
Question 6
Program that reads a string with multiple words and creates a new string which

© CS-DEPT DPS MATHURA ROAD


capitalises the first character of each word.
str = input("Enter the string ") Output :
length = len(str)
newstr = '' Enter string: i learn python
newstr +=str[0].upper() New string is : I Learn Python
i=1
while i < length:
if str[i] == ' ' and str[i+1] != ' ':
newstr+=str[i]
newstr+=str[i+1].upper()
i+=2
else:
newstr+=str[i]
i+=1
print("New string is ", newstr) 51
XI
Question 7
Program to accept a string and count and display the number of words which are

© CS-DEPT DPS MATHURA ROAD


starting with a vowel
str=input("Enter a string:") Output :
l=len(str)
p=0 Enter a string : i eat
ctr=0 food
while p<=l-1: No of words starting with
if p==0: vowel - 2
if str[p] in "aeiouAEIOU" :
ctr+=1
elif str[p] == " " and str[p+1] != " ":
if str[p+1] in "aeiouAEIOU" :
ctr+=1
p+=1
print("No. of words starting with vowel - ",ctr)
52
XI
Question 7
Program to accept a string and count and display the number of words which are

© CS-DEPT DPS MATHURA ROAD


starting with a vowel

str=input("Enter a string:") Output :


l=len(str)
s=str.split() Enter a string : i eat
ctr=0 food
for i in s: No of words starting with
if i[0] in "aeiouAEIOU": vowel - 2
ctr+=1
print("No. of words starting with vowel - ",ctr)

53
XI
Question 8
Program that reads a string and a substring, and then display the number of

© CS-DEPT DPS MATHURA ROAD


occurrences of that given substring in the string.
string=input("Enter a string - ") Output :
sub=input("Enter a substring - ")
lenstr=len(string)
lensub=len(sub)
Enter a string: i learn learn
start=ctr=0 python
end=lenstr
while True:
pos = string.find(sub,start,end) Enter a substring: learn
if pos != -1: No of occurrences of learn=2
ctr+=1
start=pos+lensub
else:
break
if start>=lenstr:
break
print("No of occurences of ",sub, "=", ctr)
54
XI
Question 9
Write the equivalent code of islower() for a string. Accept a string. It should print

© CS-DEPT DPS MATHURA ROAD


True if the string has only lowercase letter.

str=input("Enter a String:") Output :


length = len(str)
valid=True Enter a String: money
for i in range(length): True
if (str[i]>="A" and str[i]<="Z"):
valid=False
break

print(valid)

55
XI
Question 10
Write the equivalent code of upper() for a string. Accept a string. It should convert

© CS-DEPT DPS MATHURA ROAD


all lowercase letters to uppercase.

str=input("enter String - ") Output :


newstr=""
for ch in str: Enter a character:
if ch >="a" and ch<="z": programming
newstr+=chr(ord(ch)-32) New String :PROGRAMMING
else:
newstr=newstr+ch

print("New String :",newstr)

56
XI
Question 11
Write a program to enter a string and form an integer by extracting all digits

© CS-DEPT DPS MATHURA ROAD


from the string in the order they occurred.

str=input("enter string-") Output :


num=0
for ch in str: Enter string : raj456
if ch.isdigit(): String entered : raj456
num = num*10+int(ch) Extracted number : 456
print("String entered:",str)
print("Extracted number:",num)

57
XI
Question 12
Write a program to accept an identifier and check for its validity. An identifier is valid if it
is starting with a letter or underscore (_) followed by underscore (_ ) and any

© CS-DEPT DPS MATHURA ROAD


alphanumeric character.
import keyword Output :
str=input("Enter a Identifier: ")
valid = True; valid=str[0].isalpha() or str[0]=='_'
if keyword.iskeyword(str):
Enter a Identifier : _ROLLNO
valid = False Valid
length = len(str);
if valid==True:
for i in range(1,length):
if not str[i].isalnum() and str[i]!="_":
valid=False
print(str, " cannot be an identifier ")
break
else:
print(str, " is a Valid identifier")
else:
print(str, " cannot be an identifier ")
58
XI
Question 13
Write a program that accepts a string. Encrypt the string on the basis of given

© CS-DEPT DPS MATHURA ROAD


criteria and print the encrypted string:
● Every letter and digit should be replaced by the next character.
● 9 should be replaced by 0 and
● Z/z should be replaced by A/a.
● All spaces should be changed to *.
● All other special characters should remain unchanged

59
XI
Solution
str=input("Enter a string-")
newstr=""

© CS-DEPT DPS MATHURA ROAD


newch=""
for ch in str:
if ch.isalnum():
if ch=="z":
newch="a"
elif ch =="9":
newch="0"
else:
n=ord(ch)+1
newch=chr(n)
elif ch.isspace():
newch="*"
else :
newch=ch
newstr+=newch
print("Original string -",str)
print("Changed String –" ,newstr) 60
XI
Question 14
Write a program to input the full name (First name, Middle name (optional), and Last
name) of a person, and then display the name in abbreviated form.

© CS-DEPT DPS MATHURA ROAD


For example:
(i) If the name is “Saif Ali Khan”, the output should be “S. A. Khan”
(ii) If the name is “Priyanka Chopra”, the output should be P. Chopra

name = input("enter your name : ")


l=name.split()
newstr=''
for i in range(len(l)-1):
newstr = newstr + l[i][0].capitalize() + '.'
newstr = newstr + l[len(l) - 1].title()
print("Required name is : ",newstr)
61
XI
Another solution:
fn=input("Enter first name: ") Output :

© CS-DEPT DPS MATHURA ROAD


mn=input("Enter middle name: ")
ln=input("Enter last name: ") Enter first name:Saif
if (fn=='' or ln==''): Enter middle name:Ali
print("first name and last are mandatory") Enter last name:Khan
else:
if (mn==''): S.A.Khan
shortName=fn[0]+'. '+ln
else:
shortName=fn[0]+'. '+mn[0]+'. '+ln
print(shortName)

62
XI
Another solution:

© CS-DEPT DPS MATHURA ROAD


name = input("enter your name: ")
x=name[::-1]
m = x.find(" ")
str1= name[0].capitalize()+". "
for i in range(len(name)-m-1):
if name[i]==" ":
str1+=name[i+1].capitalize()+". "
str1+=name[len(name)-m:].capitalize()
print("short form of name is",str1)

63
XI
Programs
1. Write a program to input a string and a character and count the number of times a
character appears in the string.

© CS-DEPT DPS MATHURA ROAD


2. Write a program to input n number of strings. Accept n from user. Count the number
of strings which have more than 5 characters in it (Do not use any string function)
3. Write a program to accept a string. Create a new string with all the consonants
deleted from the string.
4. Write a Python program to remove the nth index character from a nonempty string. If
input string is “python” and index is 3, Expected output :”pyton”
5. Write a menu driven program to accept a string and do the following operation as per
the choice of the user
a. Display length of string
b. Display no. of words
c. Display no. of vowels
d. Reverse string 64
XI
Find the output :
A = "Passionate Programmer"

© CS-DEPT DPS MATHURA ROAD


(i) print(len(A)) (ix) print(A[-3::-2])
(ii) print(A[3])
(x) print(A[::-3])
(iii) print(A[-3])
(iv) print(A[3:]) (xi) print(A[3:-3:3])
(v) print(A[-3:]) (xii) print(A[3:-3:-3])
(vi) print(A[::3]) (xiii) print(len(A[3:]))
(vii) print(A[3::]) (xiv) print(len(A[-3:]))
(viii) print(A[3::-2])
(xv) print(len(A[::-3]))

65
XI
Solution :

© CS-DEPT DPS MATHURA ROAD


(i) print(len(A)) 21 (ix) print(A[-3::-2]) magr tnisP
(ii) print(A[3]) s
(x) print(A[::-3]) rmgPtos
(iii) print(A[-3]) m
(xi) print(A[3:-3:3]) snerr
(iv) print(A[3:]) sionate Programmer
(v) print(A[-3:]) mer (xii) print(A[3:-3:-3]) blank string
(vi) print(A[::3]) Psnerrm (xiii) print(len(A[3:])) 18
(vii) print(A[3::]) sionate Programmer (xiv) print(len(A[-3:])) 3
(viii) print(A[3::-2]) sa (xv) print(len(A[::-3])) 7

A = "Passionate Programmer"
66
XI
Find the output :
s="ComPutEr"

© CS-DEPT DPS MATHURA ROAD


for i in s:
if i in 'aeiou':
print('*',end='')
elif i.isupper():
print(i,end='')
else: print('-')

67
XI
Solution:
s="ComPutEr"

© CS-DEPT DPS MATHURA ROAD


for i in s:
if i in 'aeiou':
print('*',end='')
elif i.isupper():
C*-
print(i,end='') P*-
else: print('-') E-

68
XI
Find the output :
Name = "ComPUteR"

© CS-DEPT DPS MATHURA ROAD


for x in range(0,len(Name)):
if Name[x].islower():
print(Name[x].capitalize(), end='')
elif Name[x].isupper():
if x%2==0:
print (chr(ord(Name[x])+32),end='*')
else:
print(Name[x-1])

69
XI
Solution:
Name = "ComPUteR"

© CS-DEPT DPS MATHURA ROAD


for x in range(0,len(Name)):
if Name[x].islower():
print(Name[x].capitalize(), end='')
elif Name[x].isupper():
if x%2==0:
print (chr(ord(Name[x])+32),end='*') c*OMm
else: u*TEe
print(Name[x-1])

70
XI
Find the output :
Text1="AIsScE 2019"

© CS-DEPT DPS MATHURA ROAD


Text2=""
i=0
while i < len(Text1):
if Text1[i] >="0" and Text1[i] <"9":
val=int(Text1[i])
val=val+1
Text2=Text2+str(val)
elif Text1[i] >="A" and Text1[i] <="Z":
Text2=Text2+(Text1[i+1])
else:
Text2=Text2+"*"
i+=1
print(Text2)
71
XI
Solution :
Text1="AIsScE 2019"

© CS-DEPT DPS MATHURA ROAD


Text2=""
i=0
while i < len(Text1): I
if Text1[i] >="0" and Text1[i] <"9": Is
val=int(Text1[i]) Is*
val=val+1 Is*c
Is*c*
Text2=Text2+str(val)
Is*c*
elif Text1[i] >="A" and Text1[i] <="Z":
Is*c* *
Text2=Text2+(Text1[i+1]) Is*c* *3
else: Is*c* *31
Text2=Text2+"*" Is*c* *312
i+=1 Is*c* *312*
print(Text2)
72
XI
Find the output

© CS-DEPT DPS MATHURA ROAD


1. word = 'DPS:Mathura:Road'
print(word.split(':')) # Splitting at ':'

2. word = 'CatBatSatFatOr'
for i in range(0, len(word), 3): # Splitting at 3
print(word[i:i+3])

3. txt = "apple#banana#cherry#orange"
x = txt.split("#", 1) # Splitting at ‘#’
print(x)

73
XI
Solution:

© CS-DEPT DPS MATHURA ROAD


['DPS','Mathura','Road']
1. word = 'DPS:Mathura:Road'
print(word.split(':')) # Splitting at ':'
Cat
Bat
2. word = 'CatBatSatFatOr'
Sat
for i in range(0, len(word), 3): # Splitting at 3
Fat
print(word[i:i+3])
Or
3. txt = "apple#banana#cherry#orange"
x = txt.split("#", 1) # Splitting at ‘#’
['apple','banana#cherry#orange']
print(x)

74
XI
© CS-DEPT DPS MATHURA ROAD
Happy Learning!!!

Thank you

75
XI

You might also like