0% found this document useful (0 votes)
16 views13 pages

Cs Ch-8 Strings Notes

Uploaded by

nazeema.mca06
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)
16 views13 pages

Cs Ch-8 Strings Notes

Uploaded by

nazeema.mca06
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/ 13

CHAPTER-8 STRINGS

8.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Example:
Str1= ' IIS DAMMAM '
Str2= '' IIS DAMMAM ''
Str2= ''' IIS DAMMAM '''
Str2= '' '' '' IIS DAMMAM '' '' ''
Basics of String:
 Strings are immutable in python. It means it is unchangeable. At the same memory address, the
new value cannot be stored.
 Each character has its index or can be accessed using its index and is written in square brackets ([ ]).
 IndexError: If the index value out of the range.
 Index must be an integer(positive, zero or negative).
 Strings are stored each character in contiguous location.
 The size of string is the total number of characters present in the string.
An inbuilt function len( ) is used to return the length of the string.
Example:
Str1= IIS DAMMAM
>>> len (Str1) # gives the length of the string Str1
OUTPUT: 10
 String in python has a two-way index for each location.
Forward Indices: The index of string in forward direction starts from 0 and last index is n-1
(0, 1, 2, …….) from left to right.
Backward Indices: The index of string in backward direction starts from -1 and last index is
–n (-1, -2, -3,…. ) from right to left.
Example:
Str1= IIS DAMMAM
0 1 2 3 4 5 6 7 8 9
I I S D A M M A M
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> Str1[0] # gives the first character of Str1
'I'
>>> Str1[6] # gives the seventh character of Str1
'M'
>>> Str1[-10] # gives the last character of Str1 from right
'I'
>>> Str1[11] # gives error as index is out of range
IndexError: string index out of range
>>> Str1[1+5] # gives sixth character of Str1
'A'
>>> Str1[1.5] # gives error as index must be an integer
TypeError: string indices must be an integer
>>> Str1[-n] # gives the first character of the string
'I'
>>> Str1[n-1] # gives the last character of the string
'M'
 The character assignment is not supported in string because strings are immutable.
Example:
Str1= IIS DAMMAM
Str1[2] = ‘y’ # it is invalid. Individual letter assignment not allowed in python
1
8.2 String Operators:
a. Basic Operators (+, *)
b. Membership Operators ( in, not in)
c. Comparison Operators (==, !=, <, <=, >, >=)
d. Slicing
a. Basic Operators: There are two basic operators of strings:
i. String concatenation Operator (+)
ii. String repetition Operator (*)
i. String concatenation Operator: Concatenation means to join. The + operator creates a new string
by joining the two strings operand.
Example:
>>>''Hello''+''Python''
OUTPUT: 'HelloPython'
>>>''2''+''7''
OUTPUT: '27'
>>>''Python''+''3.0''
OUTPUT: 'Python3.0'
Note: You cannot concatenate numbers and strings as operands with + operator.
Example:
>>>7+'4' # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
ii. String repetition Operator: It is also known as String replication operator. It requires two types of
operands- a string and an integer number.
Example:
>>>''you'' * 3 # repeat the value of the string 3 times
OUTPUT: 'youyouyou'
>>>4*''Hello'' # repeat the value of the string 4 times
OUTPUT: 'HelloHelloHelloHello'
Note: You cannot have strings as both the operands with * operator.
Example:
>>>''you'' * ''you'' # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise, False
not in - Returns True if a character or a substring does not exist in the given string; otherwise, False
Example:
>>> "ear" in "Save Earth"
False
>>> "ve Ear" in "Save Earth"
True
>>>"Hi" not in "Save Earth"
True
>>>"8765" not in "9876543"
False
c. Comparison Operators: These operators compare two strings character by character according to their
ASCII value.

2
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
8.3 Finding the Ordinal or Unicode value of a character:
Function Description
ord(<character>) Returns ordinal value of a character
chr(<value>) Returns the corresponding character
Example:
>>> ord('b')
98
>>> chr(65)
'A'
8.4 Slice operator with Strings:
The slice operator slices a string using a range of indices.
Syntax:
string-name[start:end]
where start and end are integer indices. It returns a string from the index start (inclusive) to end (exclusive i.e.
end-1).
Important Note:
The numbers of characters in the substring will always be equal to the difference of two indices.
If the first index is not mentioned, the slice starts from 0 index.
If the second index is not mentioned, the slicing is done till the length of the string.
Negative indexes can also be used for slicing.
Example:

>>> str="data structure"


>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
3
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
Note:
If we ignore both the indexes and give step size as -1, the resulted string will be in reverse order.
>>> str[: : -1] # reverses a string
'erutcurts atad'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside theindex does not
cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus the index must
be valid and out of bounds index causes an error as there is no character to return from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
8.5 Traversing a String:
Access the elements of string, one character at a time.
Each character of a string can be accessed either using a for loop or while loop.
Example: Accessing each character of a string using for loop.
str = “IIS DAMMAM”
for ch in str :
print(ch, '-' end= ' ')
Output: I - I - S - - D - A - M - M - A - M –
Example: Accessing each character of a string using while loop.
str = 'IIS DAMMAM'
index=0
while index < len(str):
print(str[index],'-',end= ' ')
index +=1
Output: I - I - S - - D - A - M - M - A - M –

4
8.6 Built-in functions of string:
Example:
str=''data structure''
s1= ''hello365''
s2= ''python''
s3 = '4567'
s4 = ' '
s5= 'comp34%@'
s6='Hello World! Hello Hello'

S. No. Function Description Example


1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first >>> str.capitalize()
character 'Data structure'
capitalized.
3 title() Returns the string with the first letter of every >>> str.title()
word in uppercase and rest in lowercase. 'Data Structure'
4 count(str,start,end) Returns the number of times substring str s6='Hello World! Hello Hello'
occurs in the given string. >>>s6.count(‘Hello”, 12, 25)
If the start index is not given, it starts 2
searching from index 0. >>> s6.count(‘Hello’)
If end index is not given, it ends at length 3
of the string.
5 find(sub,start,end) Returns the lowest index in the string str=''data structure''
where thesubstring sub is found within the >>> str.find("ruct",5,13)
string range. 7
Returns -1 if sub is not found. >>> str.find("ruct",8,13)
-1
6 index(sub,start,end) Returns the lowest index in the string str=”data structure”
where thesubstring sub is found within the >>> str.find("ruct",5,13)7
string range. >>> str.find("ruct",8,13)
Raises an exception (ValueError) if the ValueError: substring not found
substring not found in the given string.
7 isalnum( ) True: If the characters in the string are >>>s1.isalnum( )
alphabets or numbers (without spaces). True
>>>s2.isalnum( )
False: If the characters in the string are True
empty string, white spaces or special >>>s3.isalnum( )
characters are part of the given string True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False

5
8 isalpha( ) True: If the characters in the string are only >>>s1.isalpha( )
alphabets (without spaces). False
>>>s2.isalpha( )
False: If the characters in the string are True
empty string, numeric values, white spaces or >>>s3.isalpha( )
special characters are part of the given string. False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
9 isdigit( ) True: If the characters in the string are only >>>s1.isdigit( )
numbers (without spaces). False
>>>s2.isdigit( )
False: If the characters in the string are False
>>>s3.isdigit( )
empty string, alphabets, white spaces or
True
special characters are part of the given string. >>>s4.isdigit( )
False
>>>s5.isdigit( )
False
10 islower( ) True: If all the characters in the string are >>> s1.islower()
lowercase, alphabetic character in lowercase True
along with non-alphabet characters. >>> s2.islower()
True
>>> s3.islower()
False: Empty string, upper case alphabetic
False
string, numeric string, special characters string. >>> s4.islower()
False
>>> s5.islower()
True
11 isupper( ) True: If all the characters in the string are >>> s1.isupper()
uppercase, alphabetic character in uppercase False
along with non-alphabet characters. >>> s2.isupper()
False
>>> s3.isupper()
False: Empty string, lower case alphabetic
False
string, numeric string, special characters string.
>>> s4.isupper()
False
>>> s5.isupper()
False
12 isspace( ) True: If there are only white space characters >>> " ".isspace()
(space, tab, carriage return, new line) in the True
string. >>> "".isspace()
False: Alphabets, digits, alphanumeric, special False
characters
13 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
14 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'

6
15 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> str.lstrip('dat')
'structure'
If used without any argument, it removes >>> str.lstrip('data')
theleading whitespaces. 'structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
'structure'
>>> str.lstrip('tad')
'structure'
16 rstrip( ) Returns a string after removing the trailing >>> str.rstrip('eur')
characters. (Right side). 'data struct'
If used without any argument, it removes >>> str.rstrip('rut')
thetrailing whitespaces. 'data structure'
>>> str.rstrip('tucers')
'data '
17 strip() Returns a string after removing the trailing >>>'Hello! '.strip()
characters from both sides (left and right of 'Hello! '
the string).
18 replace(oldstr, newstr) Replaces all the occurrences of old string with >>>s6.replace('o', '*')
the new string. 'Hell* W*rld! '
>>>s6.replace('Hello', 'Bye')
'Bye World! Bye'
19 join() Returns a string in which the characters in the >>> s2= ''python''
string have been joined by as separator. >>>s7='-' #separator
>>>s2.join(s7)
'p-y-t-h-o-n'
20 startswith() True: If the given string starts with the >>>str.startswith('Data')
supplied substring. True
False: If the given string doesn’t start with the >>>str.startswith('! ')
supplied substring. False
21 endswith() True: If the given string end with the >>>str.endswith('e')
supplied substring. True
False: If the given string doesn’t end with the >>>str.startswith('!')
supplied substring. False
22 split( ) Breaks a string into words and creates a list >>> str="Data Structure"
out of it. >>>str.split('t')
['Da' , 'a S', 'ruc' , 'ure']
If no delimiter is given, then words are >>> str.split( )
separated by space. ['Data', 'Structure']
23 partition() Partition the given string at the first >>>st='India is a Great
occurrence of the substring (separator) and Country'
returns the string partitioned into three parts. >>>st.partition('is')
1. Substring before the separator ('India', 'is', ' a Great Country')
2. Separator >>>st.partition('are')
3. Substring after the separator ('India is a Great Country',
If the separator is not found in the string, it ' ',' ')
returns the whole string itself and two
empty strings.
7
Exercise Programs – Page No: 188
Question 1:
Program: OUTPUT:
Str = input("Write a sentence: ")
total_length = len(Str) Write a sentence: Good Morning!
print("Total Characters: ", total_length) Total Characters: 13
total_Alpha = total_Digit = total_Special = 0 Total Alphabets: 11
for a in Str:
Total Digits: 0
if a.isalpha():
Total Special Characters: 2
total_Alpha += 1
elif a.isdigit(): Total Words in the Input: 2
total_Digit += 1
else:
total_Special += 1
print("Total Alphabets: ",total_Alpha)
print("Total Digits: ",total_Digit)
print("Total Special Characters: ",total_Special)
total_Space = 0
for b in Str:
if b.isspace():
total_Space += 1
print("Total Words in the Input :",(total_Space + 1))

Question 2:
ANSWER:
Program:
#Changing a string to title case using title() function
str=input("Enter the string:")
if str.istitle():
print("String is already in title case", str)
else:
new_str=str.title()
print("Original string is:", str)
print("New string after conversion to title case is:", new_str)

OUTPUT:
Enter the string: good evening!
Original string is: good evening!
New string after conversion to title case is: Good Evening!

Question 3:
ANSWER: We can write the program in two different ways:
I. Using replace() function
II. Without using replace() function
Program 1:
#Delete all occurrences of char from string using replace()function
str=input("Enter the string:")
char=input("Enter the character to remove from the string:")
res_str = str.replace(char, '')
print ("The string after removal of character", char, ": " + res_str)

OUTPUT:
Enter the string: Good Morning!
Enter the character to remove from the string: o
The string after removal of character o is: Gd Mrning!

8
Program 2:
#Delete all occurrences of char from string without using replace()function
str=input("Enter the string:")
char=input("Enter the character to remove from the string:")
newString = ''
#Looping through each character of string
for a in str:
#if character matches, replace it by empty string
if a == char:
#continue
newString += ''
else:
newString += a
print("The new string after deleting all occurrences of",char,"is: ",newString)

OUTPUT:
Enter the string: Good Morning!
Enter the character to remove from the string: o
The string after removal of character o is: Gd Mrning!

Question 4:
ANSWER:
Program:
str=input("Enter any string with digits:")
sum = 0
#sum all the digits
for a in str:
#Checking if a character is digit and adding it
if(a.isdigit()):
sum += int(a)
print("The sum of all digits in the string '",str,"' is:",sum)

OUTPUT:
Enter any string with digits: The cost of this table is Rs. 3450
The sum of all digits in the string ' The cost of this table is Rs. 3450 ' is: 12

Question 5:
ANSWER:
We can write the program in two different ways
I. Using replace() function
II. Without using replace() function

Method 1:
#replace all spaces with hyphen from string using replace()function.
str=input("Enter a sentence:")
new_str=str.replace(' ','-')
print("The new sentence is:",new_str)

OUTPUT:
Enter a sentence: Python has several built-in functions that allow us to work
with strings.
The new sentence is: Python-has-several-built-in-functions-that-allow-us-to-work-
with-strings.
9
Method 2:
#Replace all spaces with hyphen from string without using replace()function
Program:
str=input("Enter a sentence:")
newString = ''
#Looping through each character of string
for a in str:
#if char is space, replace it with hyphen
if a == ' ':
newString += '-'
#else leave the character as it is
else:
newString += a
#Printing the modified sentence
print("The new sentence is:",newString)

OUTPUT:
Enter a sentence: Python has several built-in functions that allow us to work
with strings.
The new sentence is: Python-has-several-built-in-functions-that-allow-us-to-work-
with-strings.

List of programs suggested by CBSE for String Manipulation.


1. Write a program to count no. of times a character occurs in a given string. (Th)
2. Write a program to replace all vowels with *. (Th)
3. Write a program to print the string in reverse order (Th)
4. Write a program that reads a string and checks whether it is a palindrome string or not.(Th, Pr)
5. Write a program to convert the case of characters. (Title, Alternate) (Th, Pr)
6. Write a program to count the number of vowels, consonants, uppercase, lowercase. (Th, Pr)
7. Write a program to count the number of alphabets, digits, special characters, and number of
words. (Th).

Note: Write 4th , 5th and 6th programs in Lab Record Book

ANSWERS
1. Write a program to count no. of times a character occurs in a given string. (Th)
We can write the program in two different ways
I. Using count() function
II. Without using count() function
Method 1: #count no. of times a character appear in a string using count()
function.
str=input("Enter a sentence:")
my_char=input("Enter a charcter to search for:")
new_str=str.count(my_char)
print("Number of times the character occurs:",new_str)

OUTPUT:
Enter a sentence: Hello
Enter a character to search for: l
Number of times the character occurs: 2

10
Method 2:#count no. of times a character appear in a string without using
count() function.
str=input("Enter a sentence:") OUTPUT:
my_char=input("Enter a charcter to search for:") Enter a sentence: Hello world!
count=0 Enter a character to search for: o
for i in str: Number of times the character
if i== my_char: occurs: 2
count += 1
print("Number of times the character occurs:",count)

2. Write a program to replaces all vowels with *. (Th)


str=input("Enter a sentence:")
char='*'
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
new_str='' #empty string
for i in range(len(str)): OUTPUT:
if str[i] in vowels: Enter a sentence: welcome
new_str+=char Original string is: welcome
else: New string is: w*lc*m*
new_str+=str[i]
print("Original string is:", str)
print("New string is:", new_str)

3. Write a program to print the string in reverse order. (Th)


ANS: We can write the program in two different ways
I. Using slicing
II. Without using slicing
Method 1: #Reversed the string using slicing.
str=input("Enter a sentence:") OUTPUT:
str2=str[::-1] Enter a sentence: welcome
print("Reversed string is:", str2) Reversed string is: emocleW
Method 2: #Reversed the string without using slicing.
str=input("Enter a sentence:")
new_str='' #empty string
length=len(str)
for i in range(-1, -length-1, -1): OUTPUT:
new_str+=str[i] Enter a sentence: welcome
print("Original string is:", str) Reversed string is: emocleW
print("Reversed string is:", new_str)

4. Write a program that reads a string and checks whether it is a palindrome string or not.(Th, Pr)
str=input("Enter a sentence:")
n=len(str)
mid=n//2 OUTPUT:
rev=-1 Enter a sentence: madam
for i in range(mid): The given string madam is a palindrome
if str[i] == str[rev]:
i=i+1
rev=rev-1
print("The given string",str, "is a palindrome")
break
else:
print("The given string",str, "is not a palindrome")
break

11
5. Write a program to convert the case of characters. (Title, Alternate) (Th, Pr)
a.) #Changing a string to title case using title() function
str=input("Enter the string:")
if str.istitle():
print("String is already in title case:", str)
else:
new_str=str.title()
print("Original string is:", str)
print("New string after conversion to title case is:", new_str)

OUTPUT:
Enter the string: good evening!
Original string is: good evening!
New string after conversion to title case is: Good Evening!

b) #Converting the case of alternate character of the string. Or converting


the case of the even position character of the string.
str=input("Enter the string:")
new_str='' #empty string
length=len(str)
for i in range(0, len(str)):
if i%2==0: #checking the even positions
if str[i].isupper():
new_str+=str[i].lower()
else:
new_str+=str[i].upper()
else:
new_str+=str[i]
print("Resulted string is:", new_str)

OUTPUT:
Enter the string: hello world
Resulted string is: HeLlO WoRlD

c) #Converting the case of alternate character of the string. Or converting


the case of the odd position character of the string.
str=input("Enter the string:")
new_str='' #empty string
length=len(str)
for i in range(0, len(str)):
if i%2!=0: #checking the odd positions
if str[i].isupper():
new_str+=str[i].lower()
else:
new_str+=str[i].upper()
else:
new_str+=str[i]
print("Resulted string is:", new_str)

OUTPUT:
Enter the string: hello world
Resulted string is: hElLo wOrLd

12
6. Write a program to count number of vowels, consonants, uppercase, lowercase. (Th, Pr)
str=input("Enter the string:")
n_cons= n_vows=n_ucase=n_lcase=0
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for ch in str:
if ch>='A' and ch<='Z':
n_ucase+=1
if ch>='a' and ch<='z':
n_lcase+=1
print("Number of upper-case letters in the given string is:", n_ucase)
print("Number of lower-case letters in the given string is:", n_lcase)
for i in range(len(str)):
if str[i] in vowels:
n_vows+=1
else:
n_cons+=1
print("Number of vowels in the given string is:", n_vows)
print("Number of consonants in the given string is:", n_cons)

OUTPUT:
Enter the string: hello world
Number of upper-case letters in the given string is: 0
Number of lower-case letters in the given string is: 10
Number of vowels in the given string is: 3
Number of consonants in the given string is: 8

7. Write a program to count the number of alphabets, digits, special characters, and number of
words. (Th)
Program:
Str = input("Write a sentence: ")
total_length = len(Str)
print("Total Characters: ", total_length)
total_Space = total_Alpha = total_Digit = total_Special = 0
for a in Str:
if a.isalpha():
total_Alpha += 1
elif a.isdigit():
total_Digit += 1
else:
total_Special += 1
print("Total Alphabets: ",total_Alpha)
print("Total Digits: ",total_Digit)
print("Total Special Characters: ",total_Special)
for b in Str:
if b.isspace():
total_Space += 1
print("Total Words in the Input :",(total_Space + 1))

OUTPUT:
Write a sentence: Good Morning!
Total Characters: 13
Total Alphabets: 11
Total Digits: 0
Total Special Characters: 2
Total Words in the Input: 2

13

You might also like