Nothing Special   »   [go: up one dir, main page]

Chapter 5 Strings - CBSE

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

5.

STRINGS IN PYTHON
Learning Objective:

After Having Studied this Chapter, You will be able to Understand : -

 Creating and Traversing Strings.


 Forward and Backward index of strings.
 String Concatenation, Replication and Membership Operator.
 Common String Methods.
 String Slices.

CBSE Syllabus

Strings: introduction, indexing, string operations (concatenation,


repetition, membership & slicing), traversing a string using
loops, built-in functions: len(), capitalize(), title(), lower(),
upper(), count(), find(), index(), endswith(), startswith(),
isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(),
lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
5.1 INTRODUCTION

The power of python lies in its one of very strong data type named strings.

Like many other popular programming languages, strings in Python are arrays of bytes
representing Unicode characters. However, Python does not have a character data
type, a single character is simply a string with a length of 1.

String literals in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".


Consider the following code snippet.
5.2 CREATING AND ACCESSING STRING IN PYTHON

Strings can be created by enclosing characters inside a single quote or double quotes
and assigning to the variable. Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.

>>> s = “Hello Python”.

Above is a simple way of creating the string.

Python indexes its strings in two ways. One is forward indexing and other is backward
indexing. Let’s look at the below example to have better understanding of same.
Backward Indexing

Forward Indexing

First character H would start from 0 and last character’s index would be 11 while
accessing forwardly.

In backward accessing, first character H would be at index -12 and last character would
be at index -1.

Let’s understand strings in python through small program constructs.

Get the character at position 1 (remember that the first character has the
position 0):

Program 1:Printing 2nd character in the string.


a = "Hello, World!"
print(a[1])

Output
e

Program 2: finding the length of the string

The len() method returns the length of a string:


a = "HelloWorld"
print(len(a))

Output
10

Program 3: Printing the 0th character in the string

a=input("enter a string : ")


print(a[0])
Output
>>>enter a string : monika
>>>m

Program 4: Printing the last character in the string

a=input("enter a string : ")


print(a[-1])
Output
>>>enter a string : monika
>>>a

Program 5: Printing the 2nd last character in the string.

a=input("enter a string : ")


print(a[-2]
Output
>>>enter a string: monika
>>>k

Program 6: WAPS to accept a string and print entire string character by


character.
a=input("enter a string")
for i in a:
print(i)
Output
enter a string: helloworld
h
e
l
l
o
w
o
r
l
d

Program 7: WAPS to print last 2 characters of a string.

a=input("enter a string:")
for i in range(-1,-3,-1):
print(a[i])
Output
enter a string : monika
a
k

Please note this statement

for i in range(-1,-3,-1): Step


Beginning position

Last position
Program 8: WAPS to print reverse of a string

a=input("enter a string")
for i in range(-1,-len(a)-1,-1):
print(a[i])

Output
enter a string: hello
o
l
l
e
h

Program 9. WAPS to Print original as well as reverse of the string in 1 for


loop character by character.

j=0
a=input("enter a string")
for i in range(-1,-len(a)-1,-1):
print(a[j],'\t',a[i])
j+=1
Output
enter a string:hello
o
h l
e l
l e
l h
o

5.3 STRING CONCATENATION OPERATOR


Concatenation means joining the strings.
In case of strings, + is used as string concatenation operator.
Program 10: To concatenate two strings using + operator

a=input("enter first string")


b=input("enter second string")
c=a+b
print(c)
Output
enter first string :hello
enter second string: dear
hellodear

5.4 STRING REPLICATION OPERATOR


String replication operator is used to print a string as many number of times, user wants.
Example
3*Hello! Will print
Hello ! Hello ! Hello
Another example
print(2*”6”)
66

Program 11: WAPS to print following pattern using string replication


operator
*
**
***
****
*****
print('*')
print(2*'*')
print(3*'*')
print(4*'*')
print(5*'*')
5.5 MEMBERSHIP OPERATOR:
There are two membership operators.in and not in are the names of operators.
Membership Operator Result
In Results true if character or substring
exists in main string.
not in Results true if the character or string does
not exists in main string.

Let’s look at the examples


“y” in “python” : gives true.
“hon” in “python” : gives true.
“Hon” in “python”: gives false as H is capital in the substring.
“y” not In python : gives false.
“hon” not in python: gives false.
“Hon” not in python: gives True.

Program: # WAPS to accept a main string and substring and check if the
substring is a part of the main string or not using in operator.
a=input("enter a main string")
b=input("enter a substring")
if(b in a):
print(b," is substring of ",a)
else:
print(b," is not substring of ",a)
Program : # WAPP to accept a main string and substring and check if
the substring is a part of the main string or not using not in
operator.

a=input("enter a main string")


b=input("enter a substring")
if(b not in a):
print(b," is not substring of ",a)
else:
print(b," is substring of ",a)
5.6 COMPARISON OPERATORS IN PYTHON
The main comparison operators like ,<,>,==,!=,>= and <= are same like comparison
operators as like all programming languages. These are also called relational operators.
Python uses ASCII values known as ordinal values to calculate the value of the string.
The most common ordinal values for maximum strings is
Characters Ordinal Values
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

We can calculate the ordinal value of the string by adding the values of each character
in the string.
Lets consider the below given examples
‘a’ >’A’ As Ordinal Value of A is 65 whereas ordinal value of ‘a’ is 97
‘ABC’ > ‘AB’ As Ordinal Value of ‘ABC’ is more than ordinal value of ‘AB’
‘abc’ Will give false as ordinal value of ‘abc’ is 294 whereas ordinal value of
<=’ABCD’ ‘ABCD’ is 266.
‘abcd’>’abcD’ Will give true because of obvious reasons.
‘ab’>=’ab’ Will give true as >= means either greater than or equal to.
‘ab’<=’ab’ Will give true as <= means either less than or equal to.
FINDING ORDINAL VALUE OF SINGLE CHARACTER
Bulit In function ord( ) is used to find the ordinal value of a character in python.
Consider the example given below

ord( ) function is used for single


character. It can’t be used for
strings. However ord( ) function
can be used for escape
sequences.

ord( ) function is used for single character. It can’t be used for string
FINDING CHARACTER CORROSPONDING TO ORDINAL VALUE
Opposite of ord( ) is chr( ) function.chr( ) function returns the character corresponding to
the ordinal value. Consider the example given below.

String Manipulation
1. WAP to count the number of characters in an input string.
a=input("enter string")
c=0
for i in a:
c=c+1
print(c)
2. WAP to count the number of vowels in an input string.

c=0
str=input("Enter the string ")
for i in str:
if i in "aeiouAEIOU":
c=c+1
print(c)

3. WAP to input your name and print each character of your name in same
line with a space between.

n = input("Enter your name: ")


for i in n:
print(i,end=" ")

4.WAPS to accept a main string and a substring and check if substring exists in
main string

a=input("enter main string")


b=input("enter sub string")
if b in a:
print(b,"exists in ",a)
else:
print(b,"does not exist in ",a)
5.WAPS to accept a ord value and print character corrosponding to it.
a=int(input("enter a number"))
print(chr(a))
6.WAPS to accept a character and print ord value to it.
a=input("enter a number
print(ord(a))

8.WAP to replace all characters other than alphabets and numbers to space.

a=input("Enter your name\n")


list=[]
s=""
for i in range(0,len(a)):
if (a[i]>="a" and a[i]<="z") or (a[i]>="A" and a[i]<="Z") or (a[i]>="0"
and a[i]<="9"):
s=s+str(a[i])
else:
s=s+" "
print(s)

9. WAP to capitalize first letter of the user entered string.


a=input("enter the string")
x=0
b=''
if ord(a[0])>=97 and ord(a[0])<=122:
x=ord(a[0])-32
b=b+chr(x)+a[1:]
print(b)

10.WAP that capitalizes every alternate letter of the user entered string.

a=input("enter the string")


b=''
for i in range(0,len(a)):
if ord(a[i])>=97 and ord(a[i])<=122 and i%2==0:
b=b+chr(ord(a[i])-32)
else:
b=b+a[i]
print(b)
11.WAPS to accept a string and find the count of uppercase, lowercase and digits.
lc=uc=dc=0
name=input("enter a string: ")
for a in name:
if ord(a)>=97 and ord(a)<=122 :
uc+=1
elif ord(a)>=65 and ord(a)<=90:
lc+=1
elif ord(a)>=48 and ord(a)<=57:
dc+=1
print("The count of uppercase letters is",uc)
print("The count of lowercase letters is",lc)
print("The count of digits is",dc)
12.WAP to enter a string and check if there are digits in the string. If digits are
present find sum of digits otherwise print the message ‘No digits’.

s=0
name=input("enter a string: ")
for a in name:
if ord(a)>=48 and ord(a)<=57:
s=s+int(a)
print("The sum is",s)
13.WAP to enter a string and count the no of words , no of alpha numeric
characters and special characters.

w=0
x=0
s=0
a=input("enter string")
for i in range(0,len(a)):
if a[i]==' ':
w=w+1
if (ord(a[i])>=97 and ord(a[i])<=122) or (ord(a[i])>=65 and ord(a[i])<=90)
or (ord(a[i])>=48 and ord(a[i])<=57):
x=x+1
else:
s=s+1
print("the count of words is",w+1)
print("the count of alphanumeric characters is",x)
print("the count of special characters is",s)
14.WAP to enter a string and convert all upper case to lower case and viceversa.
a=input("enter string")
b=''
for i in range(0,len(a)):
if ord(a[i])>=65 and ord(a[i])<=90:
b=b+chr(ord(a[i])+32)
elif ord(a[i])>=97 and ord(a[i])<=122:
b=b+chr(ord(a[i])-32)
print(b)
15.WAP to keep on entering strings till user says ‘y’ and convert all upper case to
lower case and viceversa.
ans='yes'
while ans=='yes':
a=input("enter string")
b=''
for i in range(0,len(a)):
if ord(a[i])>=65 and ord(a[i])<=90:
b=b+chr(ord(a[i])+32)
elif ord(a[i])>=97 and ord(a[i])<=122:
b=b+chr(ord(a[i])-32)
print(b)
ans=input("do you want to continue or not")
16.#enter a string reverse the string
a=input("enter the string")
x=''
for i in range(len(a)-1,-1,-1):
x=x+a[i]
print(x)

17. #enter a string and check if its palindrome or


#using another string

a=input("enter the string")


x=''
for i in range(len(a)-1,-1,-1):
x=x+a[i]
if x==a:
print("palindrome")
else:
print("not palindrome")
18. #enter a string and check if its palindrome or
#using another string

name=input("enter a string : ")


mid=int(len(name)//2)
rev=-1
flag=1
for i in range(0,mid,1):
If name[i]!=name[rev]:
flag=0
break
rev=rev-1
if flag==1:
print("palindrome")
else:
print("not palindrome")

Output
enter a string : malayalam
palindrome

2. WAPS to count the number of vowels in a string.

c=0
name=input("enter a string: ")
for a in name:
if a=='a' or a=='e' or a=='i' or a=='o'or a=='u':
c+=1
print("The count of vowels is",c)

Output
enter a string: hello be here
The count of vowels is 5

Find the output of the following code:


OldText="EGoveRNance"
n=len(OldText)
NewText=""
for i in range (n):
if ord(OldText[i])>=65 and ord(OldText[i])<=73:
NewText+=OldText[i].lower()
elif OldText[i]=="a" or OldText[i]=="n":
NewText+="*"
elif i%2==0:
NewText+=OldText[0:3]
else:
NewText+=OldText[i].upper()
print("The New Text After Changes: ",NewText)

egEGoVEGoREGo**CEGo
******************************************************************

5.7 STRING SLICES(v imp)


String slice means to extract some part of the string from main string. If there is a string
named mystring, then mystring[n:m] will allow to extract characters between n and m-1.
n is included in the range, whereas m is not included.
Consider the example given below

0 1 2 3 4 5 6 7 8

G R A T I T U D E

-9 -8 -7 -6 -5 -4 -3 -2 -1

Word=”GRATITUDE”
word[0:9] Will print characters from subscript 0 to 9.Last subscript is not
‘GRATITUDE’ included.
word[0:7] Will print characters from subscript 0 to 6
‘GRATITU’
word[0:3] Will print characters from subscript 0 to 2
‘GRA’
word[2:5] Will print characters from subscript 2 to 5
‘ATI’
word[-9:-6] Will print characters -9,-8,-7.-6 will be excluded as last character is
‘GRA’ excluded.
word[-6:-2] Will print characters from subscript -6,-5,-4,-3.
‘TITU’

Remember, in string slice, character at the last index is not included in the
result.
In string slice, if the beginning index is missing, then python considers 0 as the
beginning index. If the last value is missing then python considers last value as length
of the string. Consider the example given below.

Word=”GRATITUDE”
word[:9] Will print characters from subscript 0 to 8.
‘GRATITUDE’
word[:3] Will print characters from subscript 0 to 2.
‘GRA’
word[3:] Will print characters from subscript 3 till last.
‘TITUDE’
word[2:5] Will print characters from subscript 2 to 4
‘ATI’
word[-9:] Will print characters from beginning till the end.
‘GRATITUDE’
word[:-6] Will print characters from beginning to the 3rd character
‘GRA’
(refer Diagram of string for better understanding)

Solved Questions
1. Question: Give the output of the following code
Ans

2. Give output of the following

d) >>>p= “Program”
a)>>>“Program”[3:5] >>>p[4:]
b) >>>“Program”[3:6] e) >>>p= “Program”
c) >>>p= “Program” >>>p[3:6]
>>>p[:4]

a)’gr’ d)’ram’
b)’gra’ e)’gra’
Ans c)’Prog’
3. Give output of the following
a) len(“Amazing School”)
b) print(“Great” +” “+ “School”)
c) print(“A” * 4 )
d) pr” in “computer”

Ans a)14
b)Great School
c)AAAA
d)False
4 Give output
a="hello"
>>> print(a[0:0])
Ans It will print nothing.

5.8 BUILT IN METHODS


1.capitalize()
capitalize( ) function capitalizes first letter of the sentence.
name="india is my country"
>>> name.capitalize()
'India is my country'
2.lstrip()
lstrip() method is used to remove left padded spaces in a given string when used without
arguments.

>>>name1=' a '
>>>name1.lstrip()
'a '
Also lstrip() function is used to remove a leading characters from string when it is used
with arguments.
Let’s look at the examples for better understanding
>>> a='Hello There'

Function and Output Explanation


a.lstrip('He') (Removes He)
'llo There'

a.lstrip('hel') Returns the same string as H


'Hello There' is different from h.

a.lstrip('her') Though her is present,but not


'Hello There' at the beginning so does not
remove any characters.

a.lstrip('leH') Opposite of Hel is leH,which


'lo There' is present,thus is
removed.Order of characters do
not matter.)

a.lstrip('ere') Nothing is removed as it is


'Hello There' not in the beginning.

a.lstrip('elH') ‘elH’ is Present in the


'lo There' beginning,order does not
matter.)

a.lstrip('The') (Nothing is removed as ‘The’


'Hello There' is in the middle of string.

3.rstrip()
rstrip() method is used to remove right padded spaces in a given string when is used
without arguments.
>>>name1=' a '
>>>name1.rstrip()
' a'
When rstrip() function is used with arguments then it removes the characters mentioned
in the arguments from the right hand side.
a="Hello There"

Function and Output Explanation


a.rstrip("ere") Removes last 3 characters from
'Hello Th' main string.

a.rstrip('eer') Removes last three characters


'Hello Th' from string. Order does not
matter.
a.rstrip('Three') Removes last five characters
'Hello ' from string. Order does not
matter.
4.strip()
strip() method is used to remove left and right padded spaces in a given string.

>>>name1=' a '
>>>name1.strip()
'a'
However if the space is in the middle of string, it does nothing.
a="hello there"
>>> a.strip()
'hello there'

5.lower()
lower() method is used to convert given string in to lower case.

>>>name1="INDIA"
>>>name1.lower()
‘india’

6. upper()
upper() method is used to convert given string in to upper case.

name='india'
name.upper()
'INDIA'
7. title()
title() method is used to convert given string in to title case. Every first character of word of a
given string is converted to title case.

name="india is my country"
name.title()
'India Is My Country'

8.swapcase()
swapcase() method is used to toggle the case of characters. If the characters are
capital, they will be converted to lower case and vice versa.
>>>name1="MoNiKa"
>>>name1.swapcase()
'mOnIkA'
13.find() method
find() method is used to find the first occurrence of particular character or string in a
given string.
name="I love python"
>>> name.find('o')
3

It finds the first occurrence of ‘o’ which is position 3. Note that the subscript starts from 0
and space is counted as 1 character.
name='I love python'
>>> name.find('ove',0,10)
3

The above example searches for a substring ‘ove’ in the string name.0 is the beginning
index from where it has to start searching and 10 is the ending index from where it has
to stop searching. Means it has to search only in string ‘I love pyth’.
14.count() method
count() method is used to count the number of times a particular character or string appears in
a given string.

name="I love python"


>>> name.count('o')
2
‘o’ occurs 2 times.
15.startswith( ) method
startswith() method is used check if the string to be checked starts with particular string or
character or not.

name="I love python"


>>> name.startswith('a')
False
16.endswith( ) method
endswith() method is used check if the string ends with particular character or string or
not.
name="I love python"
>>> name.endswith('n')
True

17. isdigit() Method

isdigit() method is used to check if the particular string is digit (number) or not and
returns Boolean value true or false.
>>>name2="123"
>>>name2.isdigit()
True
>>name1="123keyboard"
>>name1.isdigit()
False

18. isnumeric() Method


isnumeric() is similar to isdigit() method and is used check string is digit (number) or not and
returns Boolean value true or false.

>>>name2="123"
>>>name2.isnumeric()
True
>>name1="123keyboard"
>>name1.isnumeric()
False

19.isalnum() method
isalnum() method is used check string is alpha numeric string or not.

>>>name2="123"
>>>name2.isalnum()
True
>>>name1="123computer"
>>>name1.isalnum()
True
>>>name3="Monika"
>>>name3.isalnum()
True
>>> name=”hello@3”
>>>name.isalnum()
False

20. islower() Method


islower() method is used check string contains all lower case letters or not, it returns
true or false result.
>>>>name2="Monika"
>>>name2.islower()
False
>>>name1="monika"
>>>name1.islower()
True

20. isupper() Method


isupper() method is used check string contains all upper case letters or not, it returns
true or false result.
>>>>name2="HELLO"
>>>name2.isupper()
True
>>>name1="hello"
>>>name1.upper()
False

21. isspace() Method


isspace() method is used check string contains space only or not.
>>>name2=" "
>>>name2.isspace()
True
>>>name1="India is my country"
>>>name1.isspace()
False

22. str() Method

str() method is used convert non string data into string type.
>>>str(576)
'576'

24. split() Method

split() method is used split a string.


name="I Love Programming in Python"
>>> name.split()
['I', 'Love', 'Programming', 'in', 'Python']

25.index() method
Index method is used to search for a character or substring. It has 3 arguments. First
specifies the string to be searched. Second specifies the beginning position from where
to start searching and third argument is the end position. This method ( ) is same as
find(), but raises an exception if string not found.
>>> name="Hello world"
>>> name.index("a",3,8)
ValueError: substring not found
>>> name.index("e",1,8)
1
26. count( ) Method
count() function in an inbuilt function in python programming language that returns the number
of occurrences of a substring in the given string.

The count() function has one compulsory and two optional parameters.
Mandatory paramater:
1)substring – string whose count is to be found.
Optional Parameters:
1)start (Optional) – starting index within the string where search starts.
2)end (Optional) – ending index within the string where search ends
>>> a="#pythonisfun#c++isnotfun"
>>> a.count("is")
2
>>> a.count("is",10,20)
1

27. replace()
The replace() method replaces a specified phrase with another specified phrase.
Example

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."

Another example

Replace the two first occurrence of the word "one":

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)

print(x)
three three was a race horse, two two was one too."

28. Partition function()

The partition() method searches for a specified string, and splits the string into
a tuple containing three elements.

The first element contains the part before the specified string.

The second element contains the specified string.

The third element contains the part after the string.

Example
Search for the word "bananas", and return a tuple with three elements:

1 - everything before the "match"


2 - the "match"
3 - everything after the "match"

Example
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
('I could eat ', 'bananas', ' all day')

29. join function

Join all items in a tuple into a string, using a hash character as separator:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)

John#Peter#Vicky

5.9 CHARACTER METHODS


1. ord() Method

ord() method is used get a ASCII value for a character.


ord("a")
97

2. chr() Method

char() method is used get a character for an ASCII value.


chr(98)
“b”

5.10 SOLVED PROGRAMS


1. WAPS to find the length of the string.

name=input("enter a string: ")


print(len(name))

2. WAPS to count the number of vowels in a string.

c=0
name=input("enter a string: ")
for a in name:
if a=='a' or a=='e' or a=='i' or a=='o'or a=='u':
c+=1
print("The count of vowels is",c)

Output
enter a string: hello be here
The count of vowels is 5

3. WAP to input your name and print each character of your name in
same line with a space between.
name=input("enter a string: ")
for a in name:
print(a,end=' ')

Output
enter a string: hello
h e l l o

4. WAPS to accept a string and find the count of lowercase letters,


uppercase letters and digits in a string.

lc=uc=dc=0
name=input("enter a string: ")
for a in name:
if a.isupper():
uc+=1
elif a.islower():
lc+=1
elif a.isdigit():
dc+=1
print("The count of uppercase letters is",uc)
print("The count of lowercase letters is",lc)
print("The count of digits is",dc)

Output
enter a string: Meditation KILLS StRess 123
The count of uppercase letters is 8
The count of lowercase letters is 13
The count of digits is 3

5. WAPS to accept a string and change the case of characters

name=input("enter a string")
print(name.swapcase())

Output
enter a stringPytHOn RocKs
pYThoN rOCkS

6. WAPS to accept a string and check if it is palindrome or not.

name=input("enter a string : ")


mid=int(len(name)//2)
rev=-1
flag=1
for i in range(0,mid,1):
if name[i]!=name[rev]:
flag=0
break
rev=rev-1
if flag==1:
print("palindrome")
else:
print("not palindrome")

Output
enter a string : malayalam
palindrome

Another solution

string=input("enter a string")
newstring=""
for i in range (1, len(string)+1):
newstring=newstring+string[-i]
if newstring==string:
print("pallindrome")
else:
print("not a pallindrome")

7. WAPS to captalize first letter of entered string.

a=input("enter a string")
print(a.capitalize())

8. WAPS to accept a string, if it contains digits, find the sum of


digits.

s=0
a=input("enter a string")
for i in a:
if i.isdigit():
s=s+int(i)
print(s)

9. WAPS to accept a main string and substring and count the number of
times substring appears in main string.
a=input("enter a string")
b=input("enter a substring")
print(a.count(b))

10. Write a program that, given a string that contains a decimal


number, prints out the decimal part of the number. For instance, if
given 5.74159, the program should print out .74159

a=input("enter a string")
x=a.find('.')
print(a[x+1:])

11.WAP that reads email-id of a person and ensure that it belongs to


domain @dpssharjah.com.

a=input("enter the string")


x=a.find('@')
if a[x+1:]=="dpssharjah.com" and x!=0:
print("valid email")
else:
print("invalid email")

12. WAP that enters a phone no with 10 characters and 2 dashes. Check
if phone no is valid. (Phone no format : 017-555-3462)

a=input("enter the string")


if len(a)==10 and a.find('-')>0:
print("valid phone number")
else:
print("invalid phone number")

13.WAPS to check if the string contains digits. If it contains digits


then add the digits and display the sum.
s=0
a=input("enter the string")
l=[]
if a.isdigit():
for i in a:
l.append(i)
for i in l:
s=s+int(i)
print(s)

14. Write a program that reads a line and displays the longest
substring of the given string having just the consonants.

line=input("enter the string")


l=len(line)
st=""
maxlength=0
lensub=0
lst=list()
for i in range(l):
if line[i] in ["a","e","i","o","u"]:
lst.append(st)
st=""
else:
st=st+line[i]
if line[i] not in ["a","e","i","o","u"]and i==l-1 :
lst.append(st)
for k in lst:
print(k,len(k))

15. WAP to accept a string and replace all punctuation


chars (!()-[]{};:'"\,<>./?@#$%^&*_~) with space.

Punct=’(!()-[]{};:'"\,< >./?@#$%^&*_~'
str=input(“Enter the string”)
for x in str:
if x in punct:
str[x]=’ ‘
print(str)

16. WAP to find the length of longest word in an


entered string.
Str=input("Enter the string")
word=Str.split()
max=len(word[0])
maxstr=word[0]
for x in range(1,len(word)):
if len(word[x])>max:
max=len(word[x])
maxstr=word[x]
print(max,maxstr)

17. WAP to find the length of longest word in an


entered string.
Consider the string str=’Global Warming’.
Write the statements/functions to implement the
following.
a. To display last 4 chars
b. To trim last 4 chars
c. To change the case of string
d. To display the position of ‘w’
e. To display the number of occurrences of ‘a’
f. To check whether string consist of digits only
or not.
a. str[-4:]
b. str[:-4]
c. print(str.swapcase())
d. print(str.index(‘W’))
e. print(str.count(‘a’))
f. print(str.isdigit())

Solved Multiple Choice Questions


1. What is the output when following statement is executed?
>>>"a"+"bc"
a) a
b) bc
c) bca
d) abc

2. What is the output when following statement is executed?


>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
3. The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_upercase
c) string.letters
d) string.lowercase_string.upercase

4. What is the output when following code is executed ?


>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]
a) olleh
b) hello
c) h
d) o

5. What arithmetic operators cannot be used with strings ?


a) +
b) *
c) –
d) All of the mentioned

6. What is the output when following code is executed ?


>>>print ("\nhello")
The output is
a) \nhello
b)
hello
c) nhello
d) error

7. What is the output when following statement is executed ?


>>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line

8. What is the output when following code is executed ?


>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld

9. What is the output of the following?


print("xyyzxyzxzxyy".count('yy'))
a) 2
b) 0
c) error
d) none of the mentioned

10. What is the output of the following?


print("xyyzxyzxzxyy".count('yy', 1))
a) 2
b) 0
c) 1
d) none of the mentioned
11. What is the output of the following?
print("xyyzxyzxzxyy".count('yy', 2))
a) 2
b) 0
c) 1
d) none of the mentioned
12. What is the output of the following?
print("xyyzxyzxzxyy".count('xyy', 0, 100))
a) 2
b) 0
c) 1
d) error
13. What is the output of the following?
print("xyyzxyzxzxyy".count('xyy', 2, 11))
a) 2
b) 0
c) 1
d) error
14. What is the output of the following?
print("xyyzxyzxzxyy".count('xyy', -10, -1))
a) 2
b) 0
c) 1
d) error
1 Answer: d
2 Answer: c
3 Answer: b
4 Answer: d
5 Answer: c
6 Answer: b
7 Answer: c
8 Answer: c
9 Answer: a
10 Answer: d
11 Answer: a
12 Answer: a
13 Answer: c
14 Answer: a
15 Answer: b
16 Answer: b
SOLVED PRACTICAL QUESTIONS
1. Give the output of the following code.

x = "hello world"
print(x[:2], x[-2:])
print(x[2:-3], x[-4:-2])

Ans he ld
llo wo or

2.

Give the output of the following code

str='''PythonSchool
GreaterNagar'''
print("Line1",str[19],end='#')
print("\t",str[4:7])
print(str*3,str[20:],sep="***")

Ans Line1 N# onS


PythonSchool
GreaterNagarPythonSchoolGreaterNagarPythonSchool
GreaterNagar***agar

3. Given a String s="PythonIsFun". If n=int(len(s)/2), then what


will be
the output of the following statements:
1>>>print(s[0:n])
2 >>>print(s[0:3])
3 >>>s[:n]
4 >>>s[n:]

Ans 1. Pytho
2. Pyt
3. Pytho
4. nIsFun
4. Give the output of the following code

a = True
b = False
c = False
if a or (b and c):
print(" PYTHON IS BEST")
else:
print("python is best")

Ans PYTHON IS BEST


5.

Give the output of the following

string = 'It goes as – ringaringa roses'


sub = 'ringa'
print(string.find( sub, 15, 25 ))

Ans 18
6. From the string S = “CARPE DIEM”. Which ranges return “DIE”
and “CAR”?

Ans
1.S[6:9]
2.S[0:3]

7. Give the output


s=”PURA VIDA”
print(s[9:15])

Ans There is no element at index 9, so it will return nothing.


8. What will be the output of the following code fragment?
A=”Amazing”
print (A[3:] , ”and” , A[:2])
print (A[2:7] , “and” , A[-7:-4])
Ans zing and Am
azing and Ama

9. Write a program that reads a string and then print it that


capitalizes every alternate letter in the string.
Ex: Input is: school
Output is: sChOoL
Ans string=input("Enter a String:")
L=len(string)
print("Original String is: ",string)
string2=""
for a in range (0,L):
if a%2==0:
string2 +=string[a]
else:
string2 +=string[a].upper()
print("Changed String is: ",string2)

10. What will be the output of the following programming code?

str="My Python Programming"


print(str[-5:-1])
print(str[1:5])

Ans (i) str[–5:–1]


'mmin'
(ii) str[1:5]
'y Py'
11. Consider the string str=”Green Revolution”.
Write statements in python to implement the following and
also give the output after functions are implemented.
(i) To replace all the occurrences of letter ‘e’ in the
string with “*”
(ii) To display the starting index for the substring ‘vo’.
(iii) To check whether string contains ‘vol’ or not.
(iv) To repeat the string 3 times.
Ans str.replace('e','*')
'Gr**n R*volution'
(ii) str.find('vo')
8
(iii) 'vol' in str
True
(iv) str*3
Green RevolutionGreen RevolutionGreen Revolution'
12. Write the Python statement and output for the following:
(i) Find the second occurrence of ‘m’ in ‘madam’.
(ii) To replace ‘o’ with ‘*’ in word ‘hello’.
(iii) To remove ‘h’ from word ‘hectic’.
(iv) To break the string 'Revolution' into 3 parts taking ‘l’
as separator.
(v) Change the case of each letter in string ‘ScHoOl’.
(vi) Whether ‘S’ exists in string ‘Schedule’ or not.
Ans (i) 'madam'.find('m',1) – 4
(ii) 'hello'.replace('o','*') – ‘hell*’
(iii) 'hectic'.lstrip('h') – ‘ectic’
(iv) 'Revolution'.partition('l') – ('revo', 'l', 'ution')
(v) "ScHoOl".swapcase() – sChOoL
(vi) ‘S’ in ‘Schedule’ – True
13. Give the output of the following code.
word="ThankGodforEverything"
print(word[:3]+word[6:])

Ans ThaodforEverything
14. Design a program to take a word as an input, and then
encode it into Pig Latin. A Pig Latin is an encrypted
word in English, which is generated by doing the
following alterations:
The first vowel occurring in the input word is placed at
the start of the new word along with the remaining
alphabet of it. The alphabet is present before the first
vowel is shifted; at the end of the new word it is
followed by “ay”.
 butler" = "utlerbay"
 "happy" = "appyhay"
 "duck" = "uckday"
 "me" = "emay"
 "bagel" = "agelbay"
"history" = "istoryhay
Find the output of the following code:
OldText="EGoveRNance"
n=len(OldText)
NewText=""
for i in range (n):
if ord(OldText[i])>=65 and ord(OldText[i])<=73:
NewText+=OldText[i].lower()
elif OldText[i]=="a" or OldText[i]=="n":
NewText+="*"
elif i%2==0:
NewText+=OldText[0:3]
else:
NewText+=OldText[i].upper()
print("The New Text After Changes: ",NewText)

Answe egEGoVEGoREGo**CEGo
r

You might also like