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

ch-8 strings 24-25 (1) (2)

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)
6 views

ch-8 strings 24-25 (1) (2)

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: It is a sequence, an orderly collection of one or more UNICODE characters or elements and each
character is indexed by an integer.
1. The characters can be a letter, digits, whitespace or any other symbols.
2. Sequence of characters enclosed in single, double or triple quotation marks.
Example:
Str1= ' IIS DAMMAM '
Str2= '' IIS DAMMAM ''
Str3= ''' IIS DAMMAM '''
Str4= '' '' '' 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 is out of the range.
⮚ Index must be an integer(positive, zero or negative).
⮚ Strings are stored each character in a contiguous location.
⮚ The size of a 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 the 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 the last index
is –n (-1, -2, -3,…. ) from right to left.
Note: If the index value is greater than the length of the string, the output will be an Index Error.
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 sixth character of Str1
'M'
>>> Str1[-n] # gives the first character of the string
>>> 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
'M'
>>> Str1[1.5] # gives error as index must be an integer
TypeError: string indices must be an integer

PAGE
>>> Str1[n-1] # gives the last character of the string
>>> Str1[9] # gives the last character of the string
'M'
String is Immutable:
⮚ The character assignment is not supported in string because strings are immutable. i.e.
the content of the string cannot be changed after it has been created.
⮚ An attempt to change the character would lead to an error.
Example:
Str1= IIS DAMMAM
Str1[2] = ‘y’ # Type Error: ‘str’ object does not support item assignment as string is immutable.
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 (*)
• String concatenation Operator: Concatenation means to join. The + operator creates a
new string by joining the two strings operand.
Example:
>>>''Hello''+''Python''
OUTPUT: 'HelloPython' #No space between two strings
>>>''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

PAGE
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.
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:stop:step]
where start and stop are integer indices. It returns a string from the index start (inclusive) to stop (exclusive i.e.
stop-1) for positive step value and for negative step value (backward indexing) it will end at (stop+1).
Important Note:
● The numbers of characters in the substring will always be equal to the difference of two indices.
● If the start value is not mentioned, the slice starts from 0 index.
● If the stop value is not mentioned, the slicing is done till the length of the string.
● If the step value is not mentioned, then by default it will take +1 step.
● Negative indexes can also be used for slicing.
● If the stop value is greater than the length of the string then it will consider the whole string without
giving any error unlike indexing.
● If step= +ve number: end’s at end-1 and start value<stop value, otherwise O/P will be an empty
string.
● if step= -ve number: end’s at end+1 and start value > stop value, otherwise O/P will be an empty
string.
PAGE
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, reason: start value> stop value
>>> 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'
>>> 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 operators with strings may have a 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'
>>>str[::-2]
'eucrsaa'
Note:
If we ignore both the indexes and give step size as -1, the resulting 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 the index does not
cause an error, in fact it prints till the end of the string.
Example:
>>>Str[14]
IndexError: string index out of range
>>> Str[14:20] # both indices are outside the bounds
' ' # returns empty string
PAGE
>>> 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 an out of bounds index causes an error as there is no character to return from the given index.
But slicing always returns to a substring or empty string, which is a 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 a 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 a 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 –
8.6 Built-in functions or Methods 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 capitalized. 'Data structure'
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 the end index is not given, it ends at the 3
length of the string.
5 find(sub,start,end) ● Returns the lowest index in the string Str=''data structure''
where the substring 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

PAGE
6 index(sub,start,end) ● Returns the lowest index in the string str=”data structure”
where the substring 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
8 isalpha( ) True: If the characters in the string are >>>s1.isalpha( )
only 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 >>>s1.isdigit( )
only 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
False: Empty string, upper case alphabetic >>> s3.islower()
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()

PAGE
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'
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 the >>> str.lstrip('data')
leading 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 the >>> str.rstrip('rut')
trailing 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')
Note: It will not change the original string 'Bye World! Bye'
as string is immutable.
19 join() Returns a string in which the characters in the >>> s2= ''python''
string have been joined by as separator. >>>s7='-' #separator
>>>s7.join(s2)
'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

PAGE
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']

if the delimiter is not present in the string,


then the string splits at whitespaces(space) i.e.
space is a default delimiter of split.
23 partition() Partition creates tuples and partition the given >>>st='India is a Great
string at the first occurrence of the substring Country'
(separator) and returns the string partitioned >>>st.partition('is')
into 3 parts. ('India', 'is', ' a Great Country')
1. Substring before the separator >>>st.partition('are')
2. Separator ('India is a Great Country',
3. Substring after the separator ' ',' ')
● If the separator is not found in the string, it
returns the whole string itself and two
empty strings.

Important Questions:
1. Differentiate between
a. capitalize() and title()
b. find() & index()
c. isalnum(), isalpha() & isdigit()
d. rstrip() & lstrip()
e. split() & partition()
f. Indexing & Slicing

2. Define with example:


a. String Indexing
b. String Slicing
c. String Traversing
d. Membership Operator
3. Learns all the programs.
4. Practice Output Questions and Error Finding Questions.

PAGE
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_Alpha = total_Digit = total_Special = 0
Total Characters: 13
for a in Str: Total Alphabets: 11
if a.isalpha(): Total Digits: 0
total_Alpha += 1 Total Special Characters: 2
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 = 0for 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
METHOD 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!

PAGE
METHOD 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:
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.

PAGE
Method 2:
#Replace all spaces with hyphen from string without using replace()function
Program:
str=input("Enter a sentence:")
newString = ''
for a in str: #Looping through each character of string
if a == ' ': #if char is space, replace it with hyphen
newString += '-'
else: #else leave the character as it is
newString += a
print("The new sentence is:",newString) #Printing the modified sentence

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.

TB EXAMPLE PROGRAMS:
1. Write a program to count no. of times a character occurs in a given string.
2. Write a program to replace all vowels with *.
3. Write a program to print the string in reverse order without creating a new string.
4. Write a program to print the string in reverse order.
ANSWERS
1. Write a program to count no. of times a character occurs in a given string.
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

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)

PAGE
2. Write a program to replaces all vowels with *.
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_str+=str[i]
New string is: w*lc*m*
print("Original string is:", str)
print("New string is:", new_str)

3. Write a program to print the string in reverse order without creating a new string.
ANS: We can write the program in two different ways
I. Using slicing
II. Without using slicing OUTPUT:
Enter a sentence: welcome
Reversed string is: emocleW
Method 1: #Reversed the string using slicing.
str=input("Enter a sentence:")
print("Reversed string is:", str[::-1])

Method 2: #Reversed the string without using slicing.


str=input("Enter a sentence:")
length=len(str) OUTPUT:
print("Reverse String is:", end='') Enter a sentence: welcome
for i in range(-1, -length-1, -1): Reversed string is: emocleW
print(str[i], end='')

4. Write a program to print the string in reverse order with creating a new string.
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)

List of programs suggested by CBSE for String Manipulation.


1. Write a program that reads a string and checks whether it is a palindrome string or not.
2. Write a program to convert the case of characters. (using Built-in method Title, without Built-in
method).
3. Write a program to count the number of vowels, consonants, uppercase, lowercase.

PAGE
1. Write a program that reads a string and checks whether it is a palindrome string or not.
Method I:Without Slicing
str1=input("Enter a sentence:")
new_str='' #empty string OUTPUT:
length=len(str1) Enter a sentence: madam
for i in range(-1, -length-1, -1):
new_str+=str1[i]
The given string madam is a palindrome
if new_str==str1:
print(str1, " is a palindrome")
else:
print(str1, " is not a palindrome")
Method II: Using slice operator
str1=input("Enter a sentence:")
str2=str1[::-1]
if str2==str1:
print(str1, "is a palindrome")
else:
print(str1, "is a not palindrome")
2. Write a program to convert the case of characters.
OUTPUT:
str=input("Enter the string:")
Enter the string: hello world
new_str='' #empty string Resulted string is: hElLo wOrLd
length=len(str)
for i in range(0, len(str)):
if str[i].isalpha(): #checking the element is alphabet or not
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)
3. Write a program to count the number of vowels, consonants, uppercase, lowercase.
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.isalpha():
if ch in vowels:
n_vows+=1
else:
n_cons+=1
if ch.isupper():
n_ucase+=1
elif ch.islower():
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)
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:
PAGE
7

You might also like