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

Ch-6 Notes and Questions

Uploaded by

kiran8800524133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Ch-6 Notes and Questions

Uploaded by

kiran8800524133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CHAPTER- 6th

STRINGS IN PYTHON

A string is a data structure in Python that represents a sequence of


characters. It is an immutable data type, meaning that once you
have created a string, you cannot change it. Strings are used widely
in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data
that can be represented as text.

Creating String in Python


We can create a string by enclosing the characters in single-quotes
or double- quotes. Python also provides triple-quotes to represent
the string, but it is generally used for multiline string or docstrings.
Example-
str1 = 'Hello Python'
print(str1)
str2 = "Hello Python"
print(str2)

str3 = '''Triple quotes are generally used for


represent the multiline or
docstring'''
print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring Access String Characters in Python
We can access the characters in a string in three ways.

 Indexing: One way is to treat strings as a list and use index values.

Example –
greet = 'hello'

# access 1st index element


print(greet[1]) # "e"

 Negative Indexing: Similar to a list, Python allows negative


indexing for its strings.

Example –
greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"

 Slicing: Access a range of characters in a string by using the


slicing operator colon :.

Example –
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"
Strings are immutable

In Python, strings are immutable. That means the characters of a


string cannot be changed.

Example –
message = 'Hola Amigos'
message[0] = 'H'
print(message)

Output:
TypeError: 'str' object does not support item assignment

Multiline String

We can also create a multiline string in Python. For this, we use triple
double quotes """ or triple single quotes '''.

Example –
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)

Output:
Never gonna give you up
Never gonna let you down
String Operators

Operator Description

+ It is known as concatenation operator used to join the


strings given either side of the operator.

* It is known as repetition operator. It concatenates the


multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-


strings of a particular string.

[:] It is known as range slice operator. It is used to access the


characters from the specified range.

In It is known as membership operator. It returns if a


particular sub-string is present in the specified string.

not in It is also a membership operator and does the exact


reverse of in. It returns true if a particular substring is not
present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in
the cases where we need to print the actual meaning of
escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by
the string.

% It is used to perform string formatting. It makes use of the


format specifiers used in C programming like %d or %f to
map their values in python. We will discuss how
formatting is done in python.
Example -
Consider the following example to understand the real use of
Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Operations


There are many operations that can be performed with strings
which makes it one of the most used data types in Python.
1. Comparison Operator
We use the == operator to compare two strings. If two strings are
equal, the operator returns True. Otherwise, it returns False.

Example -
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)

Output: False
True

2. Concatenation Operator

In Python, we can join (concatenate) two or more strings using


the + operator.

Example -
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


3. String Membership Operator

We can test if a substring exists within a string or not, using the


keyword in.

Example -
print('a' in 'program')
print('at' not in 'battle')

# Output: True
False

4. Reversing a Python String

With Accessing Characters from a string, we can also reverse


them. We can Reverse a string by writing [::-1] and the string will be
reversed.

Example –
hi = "goodforgood"
print(hi[::-1])
Output: doogrofdoog

5. String Slicing Methods


Python offers two ways to slice strings:
 The slice() method splits the array according to the provided
range parameters.
 The array slicing notation performs the same task as
the <strong>slice()</strong> method, but uses different notation.
In both cases, the returned value is a character range. Every string
behaves as a character array whose elements are accessible
through indexes. There are two ways to access array elements in
Python:
 Normal indexing accesses characters from the first to the last
(starting at 0).
 Negative indexing accesses characters in reverse order
(starting at -1).

Python's slice() method is a built-in function for extracting a


specific string part. The method works on any array-like object, such
as a string, list, or tuple.
The syntax is:

slice(start,stop,step)

The arguments are indices with the following behaviour:


 The start value is the index of the first character in the
subsequence. The default value is 0 or None.
 The stop value is the index of the first character not included
in the sequence. The default value is None.
 The final step value is the number of characters to skip
between the start and stop indices. The default value is 1 or None.
The method returns an object containing the substring character
array.
Use the slice() method to do the following:
 Extract a portion of a string with a step. Provide the start, stop,
and step values like in the following example code:
Example -

place = "There's no place like home."


print(place[slice(0,-1,2)])

Output: Teesn lc iehm


6. Python String Length
In Python, we use the len() method to find the length of a string.

Example –
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5

Python String functions


Python provides various in-built functions that are used for string
handling.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a


string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the
position of where it was found

format() Formats specified values in a string


format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a pecified value is replaced with a


specified value

rfind() Searches the string for a specified value and returns the last
position of where it was found

rindex() Searches the string for a specified value and returns the last
position of where it was found
rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the


specified separator,
and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

Note: All string methods returns new values. They do not change the original
string.

1. s.capitalize()
Capitalizes a string

>>> s = "heLLo BuDdY"


>>> s2 = s.capitalize()
>>> print(s2)

Output
Hello buddy
2. s.lower()
Converts all alphabetic characters to lowercase

>>> s = "heLLo BuDdY"


>>> s2 = s.lower()
>>> print(s2)

Output
hello buddy

3. s.upper()
Converts all alphabetic characters to uppercase

>>> s = "heLLo BuDdY"


>>> s2 = s.upper()
>>> print(s2)

Output
HELLO BUDDY

4. s.title()
Converts the first letter of each word to uppercase and
remaining letters to lowercase

>>> s = "heLLo BuDdY"


>>> s2 = s.title()
>>> print(s2)

Output
Hello Buddy
5. s.swapcase()
Swaps case of all alphabetic characters.

>>> s = "heLLo BuDdY"


>>> s2 = s.swapcase()
>>> print(s2)

Output
‘HEllO bUdDy’

6. s.count(<sub>[, <start>[, <end>]])


Returns the number of time <sub> occurs in s.

>>> s = 'Dread Thread Spread'


>>> s.count('e')
3
>>> s.count('rea')
3
>>> s.count('e', 4, 18)
2

7. s.find(<sub>, <start>, <end>)


Returns the index of the first occurrence of <sub> in s. Returns -1
if the substring is not present in the string.

>>> s = 'Dread Thread Spread'


>>> s.find('Thr')
6
>>> s.find('rea')
1
>>> s.find('rea', 4, 18)
8
>>> s.find('x')
-1

8. s.isalnum()
Returns True if all characters of the string are alphanumeric,
i.e., letters or numbers.

>>> s = "Tech50"
>>> s.isalnum()
True
>>> s = "Tech"
>>> s.isalnum()
True
>>> s = "678"
>>> s.isalnum()
True

9. s.isalpha()
Returns True if all the characters in the string are alphabets.

>>> s = "Techvidvan"
>>> s2 = "Tech50"
>>> s.isalpha()
True
>>> s2.isalpha()
False

10. s.isdigit()
Returns True if all the characters in the string are numbers.
>>> s1 = "Tech50"
>>> s2 = "56748"
>>> s1.isdigit()
False
>>> s2.isdigit()
True

11. s.islower()
Returns True if all the alphabets in the string are lowercase.

>>> s1 = "Tech"
>>> s2 = "tech"
>>> s1.islower()
False
>>> s2.islower()
True

12. s.isupper()
Returns True if all the alphabets in the string are uppercase.

>>> s1 = "Tech"
>>> s2 = "TECH"
>>> s1.isupper()
False
>>> s2.isupper()
True
13. s.lstrip([<chars>])
Removes leading characters from a string.
Removes leading whitespaces if you don’t provide a <chars>
argument.

14. s.rstrip([<chars>])
Removes trailing characters from a string.
Removes trailing whitespaces if you don’t provide a <chars>
argument.

15. s.strip([<chars>])
Removes leading and trailing characters from a string.
Removes leading and trailing whitespaces if you don’t provide
a <chars> argument.

Example of lstrip(), rstrip() and strip():

>>> s = " Techvidvan "


>>> s.lstrip()
'Techvidvan '
>>> s.rstrip()
' Techvidvan'
>>> s.strip()
'Techvidvan'
16. s.join(<iterable>)
Joins elements of an iterable into a single string. Here, s is
the separator string.

>>> s1 = ' '.join(['We', 'are', 'Coders'])


>>> print(s1)
We are Coders
>>> s2 = ':'.join(['We', 'are', 'Coders'])
>>> print(s2)
We:are:Coders

17. s.split(sep = None, maxspit = -1)


Splits a string into a list of substrings based on sep. If you don’t
pass a value to sep, it splits based on whitespaces.

>>> l = 'we are coders'.split()


>>> l
['we', 'are', 'coders']
>>> l = 'we are coders'.split('e')
>>> l
['w', ' ar', ' cod', 'rs']
MEMORY BYTES
º Astring is a sequence of characters.
We can create strings simply by enclosing characters in quotes (single, double or triple).
Positive subscript helps in accessing the string from the beginning.
Negative subscript helps in accessing the string from the end.
+ operator joins or concatenates the strings on both sides of the operator.
The * operator creates a new string concatenating multiple copies of the same string.
Operator 'in' returns true if a character exists in the given string.
Operator not in' returns true if a character does not exist in the given string.
Range Slice gives the characters from the given range using ':.
º Youcan use relational operators (> , <,>=,<=, ==, !=)to comparetwo strings.
r Python compares two strings character by character according to their ASCIlvalues.
Strings are immutable means that the content of the string cannot be changed after it has been created.
º There are many built-in functions for working with strings in Python.
º Python provides various string functions like len(), capitalize(), find(), etc.
split() method returns a list of allwords in the string using sep as the delimiter string.
upper() method returns a copy of the string converted into uppercase characters.
isdigit() method returns True if all the characters in the string are digits, otherwise returns False.
º count()function will return the total count of a given element in a string.
index() function returns index position of substring.
r strip() function performs both Istrip() and rstrip() on string.

OBJECTIVE TYPE QUESTIONS


1. Fill in the blanks.
(a) A string is a of characters.
(b) subscript helps in accessing the string from the beginning.
(c) subscript helps in accessing the string from the end.
(d) + operator the strings on both sides of the operator.
(e) The. method returns the lowest index of the substring if it is found in the given string.
(f) function returns the exact copy of the string with the first letter in uppercase.
(g) Strings cannot be modified as they are data types.
(h) The sequentialaccessing of each of the elements in a string is called string
(i) membership operator returns True if a character or substring exists in the
given string.
i) is apart of the string containing some contiguous characters from the string.
(k) The find() function returns ...

when substring is not found in the main string.


function is used to count how many times an element has occurred in a list.
(m) function returns True if the given string starts with the specified substring, else
returns False.
2. State whether the following statements are True or False.
(a) An empty string is a string that has zero number of characters.
(b) The last index number of string is length-1 or-1.
(c) "abc" * 2 will give abc*2 as output.
(d) Multiplication operator (*) replicates the string.
(e) We can combine two strings with the help of & operator.
(f) When we compare "A" = "a", it will give True as an output.
(g) String allows forward and backward type of indexing.
(h) In Python, asc() function returns corresponding Unicode value of a
character.
() The size of "" is 2.
Þ) Multiple line string created with the help of triple quotes will include end line character in the leng
(k) Astring is a mutable sequence of one or more characters.
3. Multiple Choice Questions (MCQs)
lal Which of the following is not a Python legal string operation?
() ´abc'+ 'abc' (i) 'abc' *3 (iii) ´abc' + 3 (iv) 'abc'.lower()
(b) In Python string, +and represent which of the following operations?
() Concatenation, Replication (ii) Addition, Multiplication
(iü) Neither (a) nor (b) (iv) Both (a) and (b)
(c) Which of following is not a valid string operation ?
(i) Slicing (i) Concatenation (ii) Repetition (iv) Floor
(d) How many times is the word "Python" printed in the following statement?
S= 'I love Python'
for ch in s[3:8]:
print ('Python')
(i) 11 times (ii) 8 times (iii) 3 times (iv) 5 times
(e) Which of the following is the correct syntax of String Slicing?
(0) String_name [start : end]
(ii) String name [start : step]
(ii) String name [step : end]
(iv) String name [step : start]
(f) What is the correct Python code to display the last four characters of "Digital India"?
(i) str[ -4:] (ii) str [4:] (ii) str [ *4:] (iv) str [/4:1
(g) What will be the output of the following code?
strl= "I love Python. "
strlen = len (strl)
print (strlen)
(i) 9 (ii) 29 (iii) 14 (iv) 3
(h) What will be the output of the following code?
Strl= 'My name is Nandini!
Str2 = Str1 [3:7]
strlen = len (Str2)
print (strlen)
() 4 (ii) 14 (iii) 24 (iv) 34
() Whichmethod removes all the trailing whitespaces from the right of the string?
(i) tolower() (i) upper() (ii) lstrip) (iv) rstrip()
() To concatenate means to
(i) replicate (i) join (i) split (iv) multiply
(k) function will always return tuple of 3 elements.
(i) index() (ii) split() (ii) partition() (iv) strip)
0) What will be the output of the following code?
A=Virtual Reality'
A.replace ('Virtual','Augmented')
(i) Virtual Augmented (i) Reality Augmented
(iii) Augmented Virtual (iv) Augmented Reality
(m) What will be the output of the following?
("er",2) )
Print ("ComputerScience".split
() ("Computer", "Science") (ii) ["Comput ", "Science"]
(i) ("Comput", "er Science"] (iv) ["Comput ", "er", "Science"]
(n) What is the ASCIlequivalent decimal no. for Y'?
(i) 87 (i) 88 (iii) 89 (iv) 90
(o) STR="RGBCOLOR"
colors-list (STR)
How do we delete 'B' in given List colors?
(i) del colors[2) (ii) colors.remove("8")
(ii) colors.pop(2) (iv) All of these
(p) Which of the following will give "Simon" as output?
strl="Hari, Simon, Vinod"
() print(str1[-7:-12]) (i) print(str1(-11:-7])
(iii) print(str1(-11:-6]) (iv) print(str1[-7:-11])

SOLVED QUESTIONS
1. What is a string?
Ans. A string is a sequence of characters where each character can be a letter, number or special symbol. We
can enclose characters in quotes (single, double or triple).
2. What is slicing in string?
Ans. Slicing returns the substring from the given string using slicing operator [:].
3. What is traversing astring?
Ans. Traversing a string means accessing each character one after the other by iterating through the elements
of astring using either for or while loop.
4. Write the output of the following statement:
strl = This is Mohit\'s "CS" book!
print (len (strl) )
Ans. 25

5. Consider the string str1="Green Revolution". Write statements in Python to implement the
following:
(a) To display the last four characters.
(b) To display the starting index for the substring 'vo'.
(c) To check whether the string contains 'vol' or not.
(d) To repeat the string 3 times.
Ans. (a) strl [ -4:]
'tion
(b) strl.find('vo')
8
(c)vol' in strl
True
(d) st.rl*3
'Greern Revolution Green Revolution Green
Revolution!
6. What will be the output of the following programming code?
X="AmaZing"
print (%|3:], "and", x[:2])
print (%[-7:], "and", x[-4:-2] )
print (x12:7],"and", x[-4:-1] )
Ans. Zing and An
ArnaZing and Zi
aZing and 2in
7. Consider the following code:
STR1=input ""Enter a string: ")
while len (STR1 )<=4:
if STR1 [-1] =='z':
STR1=STR1 [0:3]+'c!
elif 'a' in STR1:
STR1 = STR1 (0]+'bb!
elif not int (STR1 (0]):
STR1 = 'I'+STR1 [1:] +'z!
else:
STR1=STR1+ *
print (STR1)
What will be the output produced if the input is:
(a) lbzz (b) abcd
Ans. (a) 1bzc*
(b) endless loop because 'a' will always remain at index 0.
8. Write the output of the following code when executed:
Text=" gmail@com"
l=len (Text)
ntext="n

for i in range (0,1):


if Text [il.isupper ():
ntext=ntext+Text [i].lower )
elif Text [i].isalpha () :
ntext=ntext+Text [i].upper 0
else:
ntext=ntext+'bb !

print(ntext)
Ans. GMAILbbCOM
9. How many times is the word HELLO' printed in the following statement?
S='python rocks!
for ch in s[3:8] :
print ('Hello')
Ans. 5 times

10. Find the output of the following:


word = 'green vegetables
print (word. find ('g', 2))
print (wOrd. find ('veg' , 2))
print (word.find ('tab', 4, 15))
print (word. find ('eg' ,6, 8))
Ans. Output:

10
-1
11. How can you create an empty string?
IS. An empty string can be created by using either double quotes (" )or single quotes () and assigning it
to a variable.
12. Differentiate between indexing and traversing of string
index value is e
Ans. Indexing: Accessing individual characters of the string by using the subscript or
indexing. The indexspecifies thecharacter to be accessed in the string and is written in square brackets (1
Traversing: Accessing each character one after the other by iterating through the elements of a string using
either for or while loop.
13. Why is string an immutable data type?
that is why it is an imm.ot.
Ans. The contents of the string cannot be changed after it has been created;
data type.
For example,
Str1='Sound'
Str1[0]='P'
would result in - TypeError: 'str' object does not support item assignment.
14. A string called str1 contains whitespaces at the left of the string as given.
Python Program"
Write the command to delete the spaces.
Ans. The command is: strl.lstrip ()
15. What will be the value stored in bval upon execution if two strings strl and str2 are taken as "Delhi" and
"New Delhi"?
(i) bval = strl > str2 (ii) bval = strl.lower () < str2
Ans. (i) False (iü) False
16. Write a Python code to access each character, one by one, of string 'hello'.
Ans. Code:
for ch in hello :
print (ch)
Output:

17. Write a program tocount the number of vowels in the string 'pineapple'.
Ans. Code:
WOrd = 'pineapple'
Count = 0
for letter in word:
if letter in (i', u', 'a', 'e', 'o'):
Count=count+ 1
print (count)
Output:
4

18. What will be the output of the following program snippet?


strl = "aNDarIeL"
nstr =

for i in range (len (strl)):


if strl [i].isupper (0:
nstr nstr + str1
else:
[i].lower ()
nstr = nstr + strl [i.upper ()
print (nstr)
Ans. The output is:
AndARiEl
19. Write the output of the following program:
Str=" CBSE Digital India"
for i in range (len (Str) -1,0, -l) :
if St [i] .isupper ():
print (Str [i].lower (),end="" )
elif i%2==0:
if Str [i) .islower ():
print (Str [i).upper () , end="")
else:
print ("@", end="")
Ans. INi@AIId@esb

20. (a) Consider the following string myAddress: (NCERT)


myAddress = "WZ-1,New Ganga Nagar,New Delhi"
What will be the output of the following string operations?
(i) print (myAddress.lower ())
(ii) print (myAddress.upper ())
(ii) print (myAddress.count ('New'))
(iv) print (myAddress.find ('New'))
(v) print (myAddress. rfind ('New'))
(vi) print (myAddress. split(',)
(vii) print (myAddress.split(' '))
(vii) print (myAddress.replace ('New', '0ld'))
(ix) print (myAddress.partition (','))
(x) print (myAddress . index ('Agra'))
Ans. () wz-1, neW ganga nagar,new delhi
(ii) Wz-1,NEW GANGA NAGAR, NEW DELHI
(iii) 2
(iv) 5
(v) 21
(vi) ['WZ-1', 'New Ganga Nagar', 'New Delhi']
(vii) [" WZ-1', 'New' ' Ganga' 'Nagar', ' New , ' Delhi']
(viii) W2-1, 0ld Ganga Nagar, Old Delhi
(ix) (WZ-1' 'New Ganga Nagar, New Delhi')
(x) ValueError : Substring not found
(b) Consider the following string mySubject: (NCERT)
nySubject = "Computer Science"
What will be the output of the following string operations?
() print (mySubject [0:len (mySubject) ])
(i) print (mySubject [-7:-1] )
(ii) print (mySubject [::2])
(iv) print (mySubject [len (mySubject) -1])
(v) print (2*mySubject )
(vi) print (mySubject [::-2])
Ans. (0) Computer Science
(ii) Scienc
(ii) Cmue cec
(iv) e
(V) Computer ScienceComputer Science
(vi) eniSrtpo
(c) Consider the following string country:
country= "Great India"
What will be the output of the following string operations(any four)?
() print (country [0:len(country) ])
(ii) print (country [-7:-1])
(iii) print (country [: :2])
(iv) print (country [len (country) -1))
(v) print (2*country)
(vi) print (country [ :3] + country [3:])
Ans. (Ö) Great India
(iü) t Indi
(iüi) GetI da
(iv) a
(v) Great IndiaGreat India
(vi) Great India
21. Write aprogram to check whether the string is a palindrome or not. (NCERT)
Ans. Code:
str=input ("Enter the String:")
l=len (str)
p=l-1
index=0
while (index<p):
if (str [index]*=str [p]) :
index=index+1
p=p-1
else:
print ("String is not a palindrome ")
break
else:
print (""String is a Palindrome")
22. Write aprogram that reads a line, then counts words and displays how many words are there in the line.
Ans. Code:
line=input ("Enter line: ")
X=line.split ()
cnt=0
for i in x:
cnt=cnt+1
print (cnt)
23. Write a program that reads a string and then prints a string that capitalizes every other letter in the string,
e.g., school becomes sChOoL.
Ans. Code:
string=input ("Enter a string: ")
length = len (string)
print ("original string:", string)
string2="n
for a in range (0, length):
if a%2==0:
string2 t= string [a)
else:
string2 t= string [a) .upper ()
print (string2)
24. and
Writedisplays
a program that reads a line, then counts how many times a substring "is" appears in the line
the count.
Ans. Code:
strl=input ("Enter line: ")
str2="js"
L=strl.split )
cnt=0
for i in L:
if i==str2:
cnt+=1
print ("Substing is appearing:", cnt)
25. Write a program that reads a string and displays the occurrence of words starting with a vowel in the
given string.
Example:
If the string content is as follows:
Updated information is simplified by official websites.
The program should display the output as:
Updated
information
is
official
Vowel words: 4
Ans. cnt=0
strl= input ("Enter a string:")
word=strl.split ()
for i in word:
if i[0) in 'aeiou' or i[0) in 'AEIOU':
cntt=l
print (i)
print ("Vowelwords:", cnt)
26. Write aprogram that reads a string and displays the longest substring of the given string.
Ans. Code:
strl=input ("Enter a string:")
wOrd=strl. split ()
maxlength=0
maxword=""
for i in word:
X = len (i)
if x>maxlength and i.isalpha () ==True:
print (i)
maxlength=x
maxword=i
Drint ("Substring with maximum length is:",maxword)
Output:
Enter a string : Hello Python
Hello
Python
Substring with maximum length is: Python
27. Write a program to remove vowels from a string.
Ans. Code:
strl=input ("Enter string:")
str2
for i in range (len (strl)):
if strl |i] not in "ieouaAOIUE":
str2- str2+t strl[ i)
print ("Original string:",strl)
print ("New string is:",str2)
Output:
Original string : "We are learning python"
New string is : "W r lrnng pythn"
28. Write a program that reads the email id of a person in the form of a string andensures that it belongs to
domain @abc-academy.ac. in (Assumption: no invalid characters are there in email-id).
Ans: # Program that reads the email id of a person
# in the form of a string and ensures that it belongs to
# domain @ abc-academy. ac.in (Assumpt ion:no invalid characters
# are there in email-id)
email=input ('Enter your email id: ')
domain='@abC-academy. ac.in'
ledo=len (domain) #ledo=length of domain
lema=len (email) #lema=length of enail
sub=email [lema-ledo:]
if sub==domain:
if ledo!=lema:
print ('It is valid email id')
else:
print(This is invalid email id- contains just the donain name')
else:
print("This email-id is either not valid or belongs to some
other domain')
29. Write a program to input a string having some digits and return
the sum of digits present in this string.
Ans. Code: (NCERT)
a=input ("Enter a string with digit:")
C=0
for i in a:
if i.isdigit () :
C+=int (i)
print (c)
30. Find the output of the following code:
S="Wow Python"
print (len (s))
print (s[0] ,s[-1]))
Ans: 10
Wn

31. Find the value stored in ctr at the


end of this code snippet:
Inystr="Darjeeling
Ctr=0
Tea has a strong
flavour"
for i in mystr:
if i in
Ctr
'aeiouAEIOU':
print (ctr)
Ans: 12

You might also like