0% found this document useful (0 votes)
30 views12 pages

Strings and String Manipulation: Ook Valuation

This document discusses string manipulation in Python, including operations such as creation, concatenation, slicing, and formatting. It provides examples of string functions, operators, and methods, alongside exercises and programming tasks to reinforce the concepts. The document also covers the immutability of strings and how to manipulate them through various techniques.

Uploaded by

murugammalr6
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)
30 views12 pages

Strings and String Manipulation: Ook Valuation

This document discusses string manipulation in Python, including operations such as creation, concatenation, slicing, and formatting. It provides examples of string functions, operators, and methods, alongside exercises and programming tasks to reinforce the concepts. The document also covers the immutability of strings and how to manipulate them through various techniques.

Uploaded by

murugammalr6
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/ 12

CHAPTER

STRINGS AND STRING MANIPULATION


8

String Manipulation The action of the fundamental operations on strings, including their creation,
­concatenation, the extraction of string segments, string matching, their comparison, discovering their
length, replacing substrings by other strings, storage, and input/output. “String Manipulation.”

Book Evaluation 7. What is stride?


a) index value of slide operation
PART I b) first argument of slice operation
c) second argument of slice operation
d) third argument of slice operation Ans. (d)
Choose the Correct Answer (1 Mark)
8. Which of the following formatting ­character
1. Which of the following is the output of the
is used to print exponential notation in u
­ pper
following python code?
case?
str1=”TamilNadu”
a) %e b) %E
print(str1[::-1])
c) %g d) %n Ans. (b)
a) Tamilnadu b) Tmlau
c) udanlimaT d) udaNlimaT Ans. (d) 9. Which of the following is used as ­placeholders
or replacement fields which get replaced
2. What will be the output of the following
along with format( ) function?
code?
a) { } b) < >
str1 = “Chennai Schools”
c) ++ d) ^^ Ans. (a)
str1[7] = “-”
a) Chennai-Schools b) Chenna-School 10. The subscript of a string may be:
c) Type error d) Chennai Ans. (c) a) Positive b) Negative
c) Both (a) and (b) d) Either (a) or (b) Ans. (d)
3. Which of the following operator is used for
concatenation?
PART II
a) + b) &
c) * d) = Ans. ()
Answer the Following Questions (2 Marks)
4. Defining strings within triple quotes allows
creating:
1. What is String?
a) Single line Strings b) Multiline Strings
 String is a data type in python, which is used to
c) Double line Strings d) Multiple Strings
handle array of characters.
 Ans. (b)
 String is a sequence of Unicode characters that
5. Strings in python: may be a combination of letters, numbers, or spe-
a) Changeable b) Mutable cial symbols enclosed within single, double or even
c) Immutable d) flexible Ans. (c) triple quotes.
Example:
6. Which of the following is the slicing ­operator? ‘Welcome to learning Python’
a) { } b) [ ] “Welcome to learning Python”
c) < > d) ( ) Ans. (b) ‘‘‘ “Welcome to learning Python” ’’’

SURYA 1
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
2. Do you modify a string in Python? C O M P UTER
 Strings in python are immutable. C O M P UTE
 Once we define a string modifications or deletion C O M P UT
is not allowed. C O M P U
 If we want to modify the string, a new string val- C O M P
ue can be assign to the existing string variable. C O M
C O
3. How will you delete a string in Python? C
We can remove entire string variable using del
command.
PROGRAM
Example:
str=”COMPUTER”
>>> str1=”How about you”
index=len(str)
>>> print (str1)
for i in str:
How about you
print (str[:index])
>>> del str1 # string str1 is deleted now
index -=1
4. What will be the output of the following
python code? Output
str1 = “School” COMPUTER
print(str1*3) COMPUTE
COMPUT
OUTPUT: COMPU
SchoolSchoolSchool COMP
COM
5. What is slicing? CO
 Slice is a substring of a main string. C
 A substring can be taken from the original string
by using [ ] operator and index or subscript 2. Write a short about the followings with
values. suitable example:
 [ ] is known as slicing operator. Using slice (a) capitalize( ) (b) swapcase( )
­operator, we have to slice one or more substrings
from a main string. (a) capitalize( ) function:
   General format of slice operation:    It is used to capitalize the first character of the
    Str [start: : end] string.
Example:
Example: >>> city = “chennai”
str1=”THIRUKKURAL” >>> print(city.capitalize())
print (str1[0:5])
Output
OUTPUT Chennai
THIRU
swapcase( ) function:
PART III    It is change case of every character to its
­opposite case vice-versa.
Example:
Answer the Following Questions (3 Marks) >>>str=”tAmilNaDu”
1. Write a Python program to display the >>>print(str.swapcase())
­given pattern Output:
TaMILnAdu

2 SURYA
XII Std - Computer Science ´ Volume 1 Chapter - 8 Strings and String Manipulation
3. What will be the output of the given python >>> print(str1.count(‘a’,0,5))
program? 2
str1 = “welcome” >>> print(str1.count(‘a’,11))
str2 = “to school” 1
str3=str1[:2]+str2[len(str2)-2:]
print(str3) Answer the Following Questions (5 Marks)

OUTPUT 1. Explain about string operators in python


weol with suitable example.
4. What is the use of format( )? Give an String Operators
­example.    Python provides the following operators for
The format( ) function used with strings is very string operations. These operators are useful to
versatile and powerful function used for formatting manipulate string.
strings. The curly braces { } are used as placehold-
ers or replacement fields which get replaced along (i) Concatenation (+)
with format( ) function. Joining of two or more strings is called as
­Concatenation. The plus (+) operator is used to
Example: concatenate strings in python.
num1=int (input(“Number 1: “))
num2=int (input(“Number 2: “)) Example
print (“The sum of { } and { } is { }”.format(num1, >>> “welcome” + “Python”
num2,(num1+num2))) ‘welcomePython’

Output (ii) Append (+ =)


Number 1: 34 Adding more strings at the end of an existing string
Number 2: 54 is known as append. The operator += is used to
The sum of 34 and 54 is 88 append a new string with an existing string.

5. Write a note about count( ) function in Example


­python. >>> str1=”Welcome to “
 Returns the number of substrings occurs within >>> str1+=”Learn Python”
the given range. >>> print (str1)
 Substring may be a single character. Welcome to Learn Python
 Range (beg and end) arguments are optional .If
it is not given, Python searched in whole string. (iii) Repeating (*)
 Search is case sensitive. The multiplication operator (*) is used to display a
string in multiple number of times.
Example:
>>> str1=”Raja Raja Chozhan” Example
>>> print(str1.count(‘Raja’)) >>> str1=”Welcome “
2 >>> print (str1*4)
>>> print(str1.count(‘r’)) Welcome Welcome Welcome Welcome
0
>>> print(str1.count(‘R’)) (iv) String slicing
2 Slice is a substring of a main string. A substring
>>> print(str1.count(‘a’)) can be taken from the original string by using [ ]
5 operator and index or subscript values. Thus, [ ] is

SURYA 3
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
also known as slicing operator. Using slice operator, length = length +1
you have to slice one or more substrings from a print(“Length of the string “,str,” is:”, length)
main string. OUTPUT
Enter a string: COMPUTER SCIENCE
General format of slice operation: Length of the string COMPUTER SCIENCE is: 16
str[start:end]
Where start is the beginning index and end is PROGRAM USING len( ) FUNCTION:
the last index value of a character in the string. str = input(“Enter a string: “)
Python takes the end value less than one from the print(“Length of the string “,str,” is:”, len(str))
actual index specified. For example, if you want to OUTPUT
slice first 4 characters from a string, you have to Enter a string: COMPUTER SCIENCE
specify it as 0 to 5. Because, python consider only Length of the string COMPUTER SCIENCE is: 16
the end value as n-1.

2. Write a program to count the occurrences


Example I : slice a single character from a string
of each word in a given string.
>>> str1=”THIRUKKURAL”
PROGRAM
>>> print (str1[0])
def word_count(str):
T
counts = dict()
Example II : slice a substring from index 0 to 4
words = str.split()
>>> print (str1[0:5])
for word in words:
THIRU
if word in counts:
counts[word] += 1
(v) Stride when slicing string
else:
When the slicing operation, you can specify a
counts[word] = 1
third argument as the stride, which refers to the
return counts
number of characters to move forward after the
s=input(“Enter a string”)
first character is retrieved from the string. The
print(word_count(s))
­default value of stride is 1.

OUTPUT
Example
Enter a string Python prgrams are crisp Thanks
>>> str1 = “Welcome to learn Python”
­Python
>>> print (str1[10:16])
{‘Python’: 2, ‘prgrams’: 1, ‘are’: 1, ‘crisp’: 1,
learn
‘Thanks’: 1}
>>> print (str1[10:16:4])
r 3. Write a program to add a prefix text to all
>>> print (str1[10:16:2]) the lines in a string.
er PROGRAM
>>> print (str1[::3]) import textwrap
Wceoenyo text =’’’String is a data type in python. Strings are
immutable, that means once you define string, it
Hands on Practice cannot be changed during
execution. Defining strings within triple quotes also
1. Write a python program to find the length allows creation of multiline strings. In a String, py-
of a string. thon allocate an index value for its each character
PROGRAM WITHOUT USING len( ) FUNCTION: which is known as
str = input(“Enter a string: “) subscript. The subscript can be positive or negative
length = 0 integer numbers’’’
for s in str:
4 SURYA
XII Std - Computer Science ´ Volume 1 Chapter - 8 Strings and String Manipulation
text_without_Indentation = textwrap.dedent(text) OUTPUT
wrapped = textwrap.fill(text_without_Indentation, Enter a string welcome
width=50) Emoclew
final_result = textwrap.indent(wrapped, ‘###’)
6. Write a program to removes all the
print()
­occurrences of a give character in a string.
print(final_result)
PROGRAM
print()
def replace(str, char):
return str.replace(char, “”)
OUTPUT
s = input(“Enter a string “)
###String is a data type in python. Strings are
c =input(‘Enter character to replace in the string ‘)
###immutable, that means once you define string,
print(“String after replacement”,replace(s,c))
it
###cannot be changed during execution. Defining
OUTPUT
###strings within triple quotes also allows creation
Enter a string welcome to python
###of multiline strings. In a String, python allocate
Enter character to replace in the string o
###an index value for its each character which is
String after replacement welcme t pythn
###known as subscript.The subscript can be
>>>
­positive
###or negative integer numbers 7. Write a program to append a string to
­another string without using += operator.
4. Write a program to print integers with ‘*’
PROGRAM:
on the right of specified width.
s = “ “;
PROGRAM
s1=input(“Enter first string “)
num = int (input(“Enter a three digit number”))
s2=input(“Enter second string “)
print(“Given Number: “, num)
s3=input(“Enter third string “)
print(“Formatted Number”+”{:*< 7d}”.format­
seq = (s1, s2, s3);
(num));
print (s.join( seq))
print()

OUTPUT
OUTPUT
Enter first string Welcome
Enter a three digit number123
Enter second string To
Given Number: 123
Enter third string Python
Formatted Number 123***
Welcome To Python
5. Write a program to create a mirror of the
8. Write a program to swap two strings.
given string. For example, “wel” = “lew“.
PROGRAM
PROGRAM:
str1 = input(“Enter First String “)
def reverse_string(str):
str2 = input(“Enter Second String “)
rstr = ‘’
print(“Strings before swap “)
index = len(str)
print(“String1 is “,str1)
while index > 0:
print(“String2 is “,str2)
rstr += str[ index - 1 ]
str1,str2=str2,str1;
index = index - 1
print(“Strings after swap “)
return rstr
print(“String1 is “,str1)
s = input(“Enter a string “)
print(“String2 is “,str2)
print(reverse_string(s))

OUTPUT
Enter First String computer
SURYA 5
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
Enter Second String science word=word+1
Strings before swap lines.append(line)
String1 is computer line = input(‘Enter Next line: ‘)
String2 is science linecount += 1
Strings after swap print(lines)
String1 is science
String2 is computer print(“Number of Lines in the given string:
“,­linecount)
9. Write a program to replace a string with
print(“Number of words in the given string:
another string without using replace().
“,word+linecount-1)
PROGRAM:
print(“Number of characters in the given string:
def replace_all (str,find,replace):
“,char)
split_str = str.split()
result = ‘’
OUTPUT
for i in split_str:
Enter First line: WELCOME TO PYTHON.
if i == find:
Ener Next line: IT IS SIMPLE.
i = replace
Enter Next line: HAPPY IN PYTHON PROGRAM
result += i + ‘ ‘
WRITING.
return result.strip()
Enter Next line:
str =input(“Enter a string “)
[‘WELCOME TO PYTHON.’, ‘IT IS SIMPLE.’, ‘HAPPY
find=input(“Enter the string to be replaced “)
IN PYTHON PROGRAM WRITING.’]
replace=input(“Enter the replacement string “)
Number of Lines in the given string: 3
print(“Given string “,str)
Number of words in the given string: 11
str=replace_all(str, find, replace)
Number of characters in the given string: 63
print(“String after repalcement “,str)
>>>

OUTPUT
Additional Questions And Answers
Enter a string Welcome To Python
Enter the string to be replaced Python
PART A
Enter the replacement string Java
Given string Welcome To Python
Choose the Best Answer
String after repalcement Welcome To Java
>>>
1. ___ is a data type in python, which is used
10. Write a program to count the number of to handle array of characters.
characters, words and lines in a given a. Character b. String
string. c. Text d. None of these Ans. (b)
PROGRAM
lines = [] 2. String is a sequence of Unicode characters
that may be a ___
line = input(‘Enter First line: ‘) a. letters b. numbers
char=0 c. special symbols d. All the above Ans. (d)
word=1 3. In Python, Strings may be enclosed within
linecount=0 ___ quotes.
while line: a. single b. double
for i in line: c. triple d. A or B or C Ans. (d)
char=char+1
if(i==’ ‘):

6 SURYA
XII Std - Computer Science ´ Volume 1 Chapter - 8 Strings and String Manipulation
4. Identify the valid string from the following. 14. Pytho provides a function ___ to change all
a. “Python” b. ‘Python’ occurrences of a particular character in a
c. “’Python”’ d. All the above Ans. (d) string.
a. replace() b. change()
5. Defining strings within ___ quotes allows
c. modify() d. mute() Ans. (a)
creation of multiline strings.
a. single b. double 15. We can remove entire string variable using
c. triple d. A or B or C Ans. (c) ___ command.
a. delete b. del
6. Strings which contains double quotes
c. erase() d. None of these Ans. (b)
should be define within ___ quotes.
a. single b. double 16. Python provides the ___ operator for string
c. triple d. A or B or C Ans. (c) operation.
a. + b. +=
7. Strings which contains single quote should
c. * d. All the above Ans. (d)
be define within ___ quotes.
a. single b. double 17. ___ is a string concatenation operator in
c. triple d. A or B or C Ans. (b) Python.
a. + b. +=
8. Which are used to access and manipulate
c. * d. All the above Ans. (a)
the strings?
a. Subscript b. Index value 18. ___ is a string append operator in Python.
c. Either A or B d. None of these Ans. (c) a. + b. +=
c. * d. All the above Ans. (b)
9. The subscript can be ___ integers.
a. positive b. negative 19. ___ is a string repeating operator in P­ ython.
c. positive or negative d. None of these a. + b. +=
 Ans. (c) c. * d. All the above Ans. (c)

10. The positive subscript ___ is assigned to 20. ___ is a string operation.
the first character of a string. a. Slicing b. Stride
a. 0 b. 1 c. Concatenation d. All the above Ans. (d)
c. n d. None of these
21. Joining of two or more strings is called as
 Ans. (a)
___.
11. The positive subscript ___ is assigned to a. Slicing b. Stride
the last character of a string. c. Concatenation d. All the above Ans. (c)
a. n b. 1
22. Adding more strings at the end of an
c. n-1 d. None of these Ans. (c)
­existing string is known as___.
12. The negative index assigned from the last a. Slicing b. Stride
character to the first character in reverse c. Concatenation d. Append Ans. ()
order begins with ___
23. The ___ is used to display a string in
a. -n b. -1
­multiple number of times.
c. –n-2 d. None of these
a. + b. +=
 Ans. (b)
c. * d. All the above Ans. (c)
13. Once we define a string ___ is not allowed.
24. ___ is a substring of a main string.
a. modifications b. deletion
a. Slice b. Stride
c. Either A or B d. None of these Ans. (c)
c. Concatenation d. All the above Ans. (a)

SURYA 7
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
25. In slicing operator, Python takes the ___ 35. ___ is the format character to represent an
value less than one from the actual index unsigned decimal integer.
specified. a. %c b. %d
a. start b. end c. %i d. %u Ans. (d)
c. middle d. None of these Ans. (b)
36. ___ is the format character to represent an
26. When the slicing operation, we can specify octal integer.
a ___ argument as the stride. a. %c b. %d
a. first b. second c. %o d. %u Ans. (c)
c. third d. fourth Ans. (c)
37. ___ is the format character to represent a
27. In slicing operation, ___ argument refers to hexadecimal integer.
the number of characters to move ­forward a. %c b. %x
after the first character is retrieved from c. %X d. Either %x or %X
the string.  Ans. (d)
a. first b. second
38. ___ is the format character to represent an
c. third d. fourth Ans. (c)
exponent notation.
28. The default value of stride is ___. a. %c b. %e
a. 0 b. 1 c. %E d. Either %e or %E
c. -1 d. None of these Ans. (b)  Ans. (d)

29. We can use ___ value as stride. 39. ___ is the format character to represent a
a. negative b. positive short number in floating point.
c. Either A or B d. None of these Ans. (c) a. %c b. %g
c. %G d. Either %g or %G
30. If we specify a ___ value as stride, it prints
 Ans. (d)
in reverse order.
a. negative b. positive 40. Escape sequences starts with a ___
c. Either A or B d. None of these Ans. (a) ­character.
a. # b. \
31. The formatting operator ___ is used to c. / d. \\ Ans. (b)
construct strings, replacing parts of the
­
41. ___ is an escape sequnce character for
strings with the data stored in variables.
form feed.
a. % b. +=
a. \f b. \F
c. * d. None of these Ans. (a)
c. \a d. \r Ans. (a)
32. ___ is the format character to represent a
42. ___ is an escape sequnce character for line
character.
feed.
a. %c b. %d
a. \f b. \n
c. %i d. %u Ans. (a)
c. \a d. \r Ans. (b)
33. ___ is the format character to represent a
43. ___ is an escape sequnce character for
signed decimal integer.
­carriage return.
a. %c b. %d
a. \f b. \F
c. %i d. Either %d or %i
c. \a d. \r Ans. (d)
 Ans. (d)
34. ___ is the format character to represent a 44. ___ is an escape sequnce character for
string. ­vertical tab.
a. %s b. %d a. \v b. \t
c. %i d. %u Ans. (a) c. \a d. \r Ans. (a)
8 SURYA
XII Std - Computer Science ´ Volume 1 Chapter - 8 Strings and String Manipulation
45. ___ is an escape sequnce character for 55. The find() function returns ___ if the
horizontal tab. ­substring does not occur in the string.
a. \f b. \t a. 0 b. 1
c. \v d. \r Ans. (b) c. -1 d. None of these Ans. (c)

46. ___ is an escape sequnce character for bell 56. ___ function returns true, if the string
sound. ­contains only letter and digit.
a. \f b. \F a. islanum() b. isalpha()
c. \a d. \r Ans. (c) c. isdigit() d. islower() Ans. (a)

47. ___ is an escape sequnce character for 57. ___ function returns true, if the string
­octal value. ­contains only letters.
a. \f b. \xHH a. islanum() b. isalpha()
c. \a d. \ooo Ans. (d) c. isdigit() d. islower() Ans. (b)

48. ___ is an escape sequnce character for 58. ___ function returns true, if the string
hexadecimal value. ­contains only numbers.
a. \f b. \xHH a. islanum() b. isalpha()
c. \a d. \ooo Ans. (b) c. isdigit() d. islower() Ans. (c)

49. The ___ function used with strings is used 59. ___ function returns the exact copy of the
for formatting strings. string with all the letters in lowercase.
a. format( ) b. strings() a. lower() b. isupper()
c. fstring() d. None of these Ans. (a) c. upper() d. islower() Ans. (a)

50. ___ function returns the length of the 60. ___ function returns the exact copy of the
string. string with all the letters in uppercase.
a. len() b. capitalize() a. lower() b. isupper()
c. center() d. find() Ans. (a) c. upper() d. islower() Ans. (c)

51. ___ function is used to capitalize the first 61. ___ function returns True if the string is in
character of the string. lowercase.
a. len() b. capitalize() a. lower() b. isupper()
c. center() d. find() Ans. (b) c. upper() d. islower() Ans. (d)

52. ___ function returns a string with the 62. ___ function returns True if the string is in
original string centered to a total width
­ uppercase.
colums. a. lower() b. isupper()
a. len() b. capitalize() c. upper() d. islower() Ans. (b)
c. center() d. find() Ans. (c)
63. ___ function returns True if the string is in
53. ___ function is used to search the first titlecase.
occurrence of the sub-string in the given a. lower() b. isupper()
string. c. upper() d. title() Ans. (d)
a. len() b. capitalize()
64. ___ function will change case of every
c. center() d. find() Ans. (d)
character to its opposite case vice-versa.
54. ___ function is returns the index at which a. swapcase() b. isupper()
the sub-string starts. c. u
­ pper() d. title() Ans. (a)
a. len() b. capitalize()
c. center() d. find() Ans. (d)

SURYA 9
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
65. ___ function returns the number of \r ASCII Carriage Return
­substrings occurs within the given range.
\t ASCII Horizontal Tab
a. count() b. ord()
\v ASCII Vertical Tab
c. chr() d. None of these Ans. (a)
\ooo Character with octal value ooo
66. ___ function returns the ASCII code of the \xHH Character with hexadecimal value HH
character.
3. Write note on membership operators in
a. count() b. ord()
­Python.
c. chr() d. None of these Ans. (b)
Membership Operators
67. ___ function returns the character    The ‘in’ and ‘not in’ operators can be used with
­represented by a ASCII code. strings to determine whether a string is present
a. count() b. ord() in another string. Therefore, these operators are
c. chr() d. None of these Ans. (c) called as Membership Operators.

68. The ___ operator can be used with strings


Example:
to determine whether a string is present in
str2=”chennai”
another string.
if str2 in str1:
a. in and not in b. in
   print (“Found”)
c. notin d. None of these Ans. (a)
else:
69. ___ operator is called as membership    print (“Not Found”)
­operator.
a. in and not in b. in Output : 1
c. notin d. None of these Ans. (a) Enter a string: Chennai G HSS, Saidapet
Found
PART B Output : 2
Enter a string: Govt G HSS, Ashok Nagar
1. Write note on escape sequnce in Python. Not Found
Escape sequences starts with a backslash and it
4. Write program in Python to display the
can be interpreted differently. When we have use
­following pattern.
single quote to represent a string, all the single
*
quotes inside the string must be escaped. Similar is
**
the case with double quotes.
***
   Ex. \n – new line
****
2. List the escape sequences supported by *****
Python. PROGRAM
Escape Description str1=’ * ‘
Sequence i=1
while i<=5:
\newline Backlash and newline ignored
   print (str1*i)
\\ Backlash
   i+=1
\* Single quote
\” Double quote Output
\a ASCII Bell *
\b ASCII Backspace **
\f ASCII Formfeed ***
\n ASCII Linefeed ****
*****
10 SURYA
XII Std - Computer Science ´ Volume 1 Chapter - 8 Strings and String Manipulation
3. Write program in Python to check whether
PART IV
the given string is palindrome or not
str1 = input (“Enter a string: “)
1. How will you create a string in Python?
str2 = ‘ ‘
 String in Python can be created using single or
index=-1
double or even triple quotes.
for i in str1:
 Strings which contains double quotes should be
   str2 += str1[index]
defi ne within triple quotes.
   index -= 1
 Defi ning strings within triple quotes also allows
print (“The given string = { } \n The Reversed string
creation of multiline strings.
= { }”.format(str1, str2))
Example:
if (str1==str2):
#double quoted string defined within double
   print (“Hence, the given string is Palindrome”)
quotes
else:
>>> print (‘’’ “Computer Science” ‘’’)
   print (“Hence, the given is not a palindrome”)
“Computer Science”
#single and double quoted multiline string defined
Output : 1
within triple quotes
Enter a string: malayalam
>>> print (‘’’ “Strings are immutable in ‘Python’,
The given string = malayalam
which means you can’t make any changes once you
The Reversed string = malayalam
declared” ‘’’)
Hence, the given string is Palindrome
“Strings are immutable in ‘Python’, which
means you can’t make any changes once you
Output : 2
declared”
Enter a string: welcome
2. How to access characters in a string? The given string = welcome
Accessing characters in a String The Reversed string = emoclew
 Once we define a string, python allocate an ­index Hence, the given string is not a palindrome
value for its each character.
4. Write a program in Python to display the
 The index values are otherwise called as ­subscript
number of vowels and consonants in the
which are used to access and ­ manipulate the
given string.
strings.
PROGRAM:
 The subscript can be positive or negative integer
str1=input (“Enter a string: “)
numbers.
str2=”aAeEiIoOuU”
 The positive subscript 0 is assigned to the first
v,c=0,0
character and n-1 to the last character, where n
for i in str1:
is the number of characters in the string.
   if i in str2:
 The negative index assigned from the last
   v+=1
­character to the first character in reverse order
else:
begins with -1.
  c+=1
Example:
print (“The given string contains { } vowels and { }
consonants”.format(v,c))
String S C H O O L
Positive 0 1 2 3 4 5 Output
subscript Enter a string: Tamilnadu School Education
Negative -6 -5 -4 -3 -2 -1 The given string contains 11 vowels and 15
subscript ­consonants

SURYA 11
Chapter - 8 Strings and String Manipulation XII Std - Computer Science ´ Volume 1
5. Write a program in Python to create an Example:
Abecedarian series. (Abecedarian refers name = “Rajarajan”
list of elements appear in alphabetical or- mark = 98
der) print (“Name: %s and Marks: %d” %(name,mark))
PROGRAM: Output
str1=”ABCDEFGH” Name: Rajarajan and Marks: 98
str2=”ate”
for i in str1: Formatting characters:
   print ((i+str2),end=’\t’) Form characters USAGE
Output %c Character
Aate Bate Cate Date Eate Fate Gate Hate %d Signed decimal i­nteger
6. Write a program that accept a string %s String
from the user and display the same after %u Unsigned decimal i­nteger
­removing vowels from it. %o Octal integer
PROGRAM: %x or %X Hexadecimal integer (lower
def rem_vowels(s): case x refers a-f; upper case
temp_str=’’ X refers A-F)
for i in s: %e or %E Exponential notation
   if i in “aAeEiIoOuU”:
%f Floating point numbers
    pass
%g or %G Short numbers in floating
  else:
point or exponential notation.
     temp_str+=i
print (“The string without vowels: “, temp_str) 2. Wrtie a program in Python that count the
str1= input (“Enter a String: “) occurrences of a character in a string.
rem_vowels (str1) PROGRAM:
def count(s, c):
Output c1=0
Enter a String: Mathematical foundations of for i in s:
­Computer Science     if i == c:
The string without vowels: Mthmtcl fndtns f Cmptr       c1+=1
Scnc    return c1
str1=input (“Enter a String: “)
PART D ch=input (“Enter a character to be searched: “)
cnt=count (str1, ch)
1. Explain briefly about String Formatting print (“The given character {} is occurs {} times in
­ perators in Python.
O the given string”.format(ch,cnt))
  The string formatting operator % is used to
construct strings, replacing parts of the strings with Output
the data stored in variables. Enter a String: Software Engineering
Syntax: Enter a character to be searched: e
(“String to be display with %val1 and %val2” The given character e is occurs 3 times in the given
%(val1, val2)) string

12 SURYA

You might also like