1st PUC Computer Science Chapter 8 Strings Notes | Class 11 Python Strings
Complete Short Notes & Exam Preparation Guide
Based on the NCERT Computer Science β Class XI textbook chapter.
π Chapter Overview
This chapter explains Strings in Python. A string is a sequence made up of one or more UNICODE characters. The chapter covers creation of strings, accessing characters, indexing, negative indexing, string length, immutability, string operations, slicing, traversal, string methods, built-in functions and handling strings using user-defined functions.
π Table of Contents
- 8.1 Introduction
- 8.2 Strings
- 8.2.1 Accessing Characters in a String
- 8.2.2 String is Immutable
- 8.3 String Operations
- 8.3.1 Concatenation
- 8.3.2 Repetition
- 8.3.3 Membership
- 8.3.4 Slicing
- 8.4 Traversing a String
- 8.5 String Methods and Built-in Functions
- 8.6 Handling Strings
- Textbook Programs
- Chapter Summary
- Textbook Exercise & Programming Problems
- Important Questions
- Quick Revision
8.1 Introduction
A sequence is an orderly collection of items and each item is indexed by an integer. The chapter introduces strings in detail.
The sequence data types introduced earlier include:
- Strings
- Lists
- Tuples
Dictionary is another data type introduced earlier and it belongs to the category of mapping.
8.2 Strings
A string can be created by enclosing one or more characters in single quotes, double quotes or triple quotes.
String Creation
str1 = 'Hello World!' str2 = "Hello World!" str3 = """Hello World!""" str4 = '''Hello World!'''
These variables represent the same string value Hello World!.
Multi-line Strings
Triple quotes can be used to extend strings over multiple lines.
str3 = """Hello World! welcome to the world of Python""" str4 = '''Hello World! welcome to the world of Python'''
8.2.1 Accessing Characters in a String
The first character from the left has index 0. If the length of the string is n, the last character has index n-1.
Hello World!
Example: Positive Indexing
str1 = 'Hello World!' str1[0] 'H' str1[6] 'W' str1[11] '!'
Index Out of Range
str1[15] IndexError: string index out of range
If the index is outside the valid range, Python gives an IndexError.
Index Expression
str1[2+4] 'W'
An index can be an expression, but the expression must evaluate to an integer.
str1[1.5] TypeError: string indices must be integers
Negative Indexing
Python also supports negative indexes. The first character from the right has index -1 and the last character from the right has index -n, where n is the length of the string.
str1[-1] '!' str1[-12] 'H'
Length of a String β len()
len() returns the length of the
string passed as its parameter.
str1 = 'Hello World!' len(str1) 12 n = len(str1) print(n) 12
For str1 = 'Hello World!', the length is
12.
str1[n-1] '!' str1[-n] 'H'
8.2.2 String is Immutable
An attempt to modify an individual character of a string results in an error.
str1 = "Hello World!" str1[1] = 'a' TypeError: 'str' object does not support item assignment
8.3 String Operations
Since a string is a sequence of characters, Python provides operations for working with strings.
| Operation | Operator / Technique | Purpose |
|---|---|---|
| Concatenation | + |
Joins two strings. |
| Repetition | * |
Repeats a string. |
| Membership | in, not in |
Checks whether a string or substring is present. |
| Slicing | [n:m] |
Extracts part of a string. |
8.3.1 Concatenation
+ operator for concatenation.
str1 = 'Hello' str2 = 'World!' str1 + str2 'HelloWorld!'
The original strings remain unchanged after concatenation.
str1 'Hello' str2 'World!'
8.3.2 Repetition
* operator to repeat a string.
str1 = 'Hello' str1 * 2 'HelloHello' str1 * 5 'HelloHelloHelloHelloHello'
8.3.3 Membership
Python provides two membership operators:
in and not in.
in Operator
The in operator returns True if the first
string appears as a substring in the second string. Otherwise,
it returns False.
str1 = 'Hello World!' 'W' in str1 True 'Wor' in str1 True 'My' in str1 False
not in Operator
The not in operator returns True when the
first string does not occur in the second string.
'My' not in str1 True 'Hello' not in str1 False
| Operator | Returns True when |
|---|---|
in |
The first string occurs in the second string. |
not in |
The first string does not occur in the second string. |
8.3.4 Slicing
For a string str1, the operation
str1[n:m] starts at index n
(inclusive) and ends before index m
(exclusive).
str1[n:m] is
m β n.
Basic Slicing
str1 = 'Hello World!' str1[1:5] 'ello' str1[7:10] 'orl'
Index Larger Than String Length
str1[3:20] 'lo World!'
An index that is too large is truncated down to the end of the string.
First Index Greater Than Second Index
str1[7:2] ''
If the first index is greater than the second index in this form, the result is an empty string.
Omitting the First Index
str1[:5] 'Hello'
If the first index is not specified, slicing starts from index 0.
Omitting the Second Index
str1[6:] 'World!'
If the second index is not specified, slicing continues to the end of the string.
Step Size
Slicing can also contain a third value representing the step size:
str1[n:m:k].
It extracts every kth character starting from
n and ending at m-1. The default step
size is 1.
str1[0:10:2] 'HloWr' str1[0:10:3] 'HlWl'
Negative Slicing
str1[-6:-1] 'World'
Reverse a String Using Slicing
str1[::-1] '!dlroW olleH'
str1[n:m] includes index n but excludes
index m.
8.4 Traversing a String
The textbook demonstrates string traversal using:
- for loop
- while loop
A. String Traversal Using for Loop
str1 = 'Hello World!'
for ch in str1:
print(ch,end = '')
Hello World!
The loop starts with the first character of the string and automatically stops after accessing the last character.
B. String Traversal Using while Loop
str1 = 'Hello World!'
index = 0
while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World!
The while loop continues while
index < len(str1) is true.
The value of index varies from 0 to
len(str1)-1.
8.5 String Methods and Built-in Functions
Python provides several built-in functions and methods for working with strings.
| Method / Function | Description | Textbook Example |
|---|---|---|
len() |
Returns the length of the given string. | len(str1) β 12 |
title() |
Converts the first letter of every word to uppercase and the remaining letters to lowercase. | str1.title() β 'Hello World!' |
lower() |
Converts uppercase letters to lowercase. | str1.lower() β 'hello world!' |
upper() |
Converts lowercase letters to uppercase. | str1.upper() β 'HELLO WORLD!' |
count(str,start,end) |
Returns the number of times a substring occurs in a string. | str1.count('Hello') β 3 |
find(str,start,end) |
Returns the index of the first occurrence of a substring. Returns -1 when the substring is not present. | str1.find('Hee') β -1 |
index(str,start,end) |
Similar to find(), but raises an exception if the substring is not present. | str1.index('Hee') β ValueError |
endswith() |
Returns True if the string ends with the supplied substring. | str1.endswith('!') β True |
startswith() |
Returns True if the string starts with the supplied substring. | str1.startswith('He') β True |
isalnum() |
Returns True when the characters are alphabets or numbers and there is no whitespace or special symbol. | 'HelloWorld2'.isalnum() β True |
islower() |
Returns True for a non-empty string with lowercase alphabetic characters according to the conditions shown in the textbook. | 'hello world!'.islower() β True |
isupper() |
Returns True for a non-empty string with uppercase alphabetic characters according to the conditions shown in the textbook. | 'HELLO WORLD!'.isupper() β True |
isspace() |
Returns True when all characters are whitespace. | ' \n \t \r'.isspace() β True |
istitle() |
Returns True if the non-empty string is in title case. | 'Hello World!'.istitle() β True |
lstrip() |
Removes spaces from the left side of the string. | ' Hello World! '.lstrip() |
rstrip() |
Removes spaces from the right side of the string. | ' Hello World! '.rstrip() |
strip() |
Removes spaces from both left and right sides. | ' Hello World! '.strip() |
replace(oldstr,newstr) |
Replaces occurrences of the old string with the new string. | str1.replace('World','Country') |
join() |
Joins the characters of a string using another string as a separator. | '-'.join('HelloWorld!') |
partition() |
Partitions a string at the first occurrence of a separator and returns three parts. | str1.partition('is') |
split() |
Returns a list of words separated by the specified delimiter. | str1.split() |
len(), title(),
lower(), upper(), count(),
find(), index(), startswith(),
endswith(), replace(), split()
and partition().
Selected Method Examples
str1 = 'hello WORLD!' str1.title() 'Hello World!' str1.lower() 'hello world!' str1.upper() 'HELLO WORLD!'
str1 = 'Hello World! Hello Hello'
str1.count('Hello')
3
str1.find('Hello')
0
str1.find('Hee')
-1
str1 = 'Hello World!'
str1.endswith('World!')
True
str1.endswith('!')
True
str1.startswith('He')
True
str1.startswith('Hee')
False
str1 = 'HelloWorld2' str1.isalnum() True str1 = 'HelloWorld!!' str1.isalnum() False
str1 = ' Hello World! ' str1.lstrip() 'Hello World! ' str1.rstrip() ' Hello World!' str1.strip() 'Hello World!'
str1 = 'Hello World!'
str1.replace('o','*')
'Hell* W*rld!'
str1.replace('World','Country')
'Hello Country!'
str1 = 'HelloWorld!' str2 = '-' str2.join(str1) 'H-e-l-l-o-W-o-r-l-d-!'
str1 = 'India is a Great Country'
str1.partition('is')
('India ', 'is', ' a Great Country')
str1 = 'India is a Great Country' str1.split() ['India', 'is', 'a', 'Great', 'Country']
8.6 Handling Strings
This section explains how user-defined functions can be used to perform different operations on strings.
Program 8-1 β Count Character Occurrences
Write a program with a user-defined function to count the number of times a character passed as an argument occurs in a string.
# Program 8-1
# Function to count the number of times a character occurs in a string
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
# end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,
"occurs in the string is:",count)
Enter a string: Today is a Holiday Enter the character to be searched: a Number of times character a occurs in the string is: 3
Program 8-2 β Replace Vowels with *
Write a user-defined function with a string as a parameter that
replaces all vowels in the string with *.
# Program 8-2
# Function to replace all vowels in the string with '*'
def replaceVowel(st):
# create an empty string
newstr = ''
for character in st:
# check if next character is a vowel
if character in 'aeiouAEIOU':
# Replace vowel with *
newstr += '*'
else:
newstr += character
return newstr
# end of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)
Enter a String: Hello World The original String is: Hello World The modified String is: H*ll* W*rld
Program 8-3 β Reverse String Without New String
Write a program to input a string and print it in reverse order without creating a new string.
# Program 8-3
# Program to display string in reverse order
st = input("Enter a string: ")
for i in range(-1,-len(st)-1,-1):
print(st[i],end='')
Enter a string: Hello World dlroW olleH
Program 8-4 β Reverse String Using Function
Write a user-defined function that reverses a string passed as a parameter and stores the reversed string in a new string.
# Program 8-4
# Function to reverse a string
def reverseString(st):
newstr = '' # create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
# end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)
Enter a String: Hello World The original String is: Hello World The reversed String is: dlroW olleH
Program 8-5 β Check Palindrome
# Program 8-5
# Function to check if string is palindrome or not
def checkPalin(st):
i = 0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
# end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")
Enter a String: kanak The given string kanak is a palindrome
Enter a String: computer The given string computer is not a palindrome
π Chapter Summary
- A string is a sequence of characters enclosed in single, double or triple quotes.
- Indexing is used to access individual characters within a string.
- The first character has index 0 and the last character has index n-1.
- Negative indexing ranges from -n to -1.
- Strings in Python are immutable.
- The
inoperator checks whether a string occurs as a substring. - The
not inoperator performs the reverse membership check. - Slicing retrieves a portion of a string using an index range.
str1[n:m]starts from n and ends before m.- A string can be traversed using a for loop or while loop.
- Python provides many built-in functions and methods for strings.
- User-defined functions can be used to perform string operations.
π Textbook Exercise
Exercise 1
Consider the following string:
mySubject = "Computer Science"
Find the output of:
print(mySubject[0:len(mySubject)])print(mySubject[-7:-1])print(mySubject[::2])print(mySubject[len(mySubject)-1])print(2*mySubject)print(mySubject[::-2])print(mySubject[:3] + mySubject[3:])print(mySubject.swapcase())print(mySubject.startswith('Comp'))print(mySubject.isalpha())
Exercise 2
Consider:
myAddress = "WZ-1,New Ganga Nagar,New Delhi"
Find the output of:
print(myAddress.lower())print(myAddress.upper())print(myAddress.count('New'))print(myAddress.find('New'))print(myAddress.rfind('New'))print(myAddress.split(','))print(myAddress.split(' '))print(myAddress.replace('New','Old'))print(myAddress.partition(','))print(myAddress.index('Agra'))
π» Textbook Programming Problems
- Write a program to input line(s) of text from the user until Enter is pressed. Count the total number of characters including white spaces, alphabets, digits, special symbols and words.
- Write a user-defined function to convert a string containing more than one word into title case.
-
Write a function
deleteChar()that takes a string and a character and creates a new string after deleting all occurrences of that character. - Input a string having some digits and write a function to return the sum of digits present in the string.
- Write a function that takes a sentence where each word is separated by a space, replaces each blank with a hyphen and returns the modified sentence.
π Important Questions
1-Mark / Very Short Answer
A string is a sequence made up of one or more UNICODE characters.
By enclosing characters in single, double or triple quotes.
The first character has index 0.
It accesses characters from the right side of the string.
-1.
It returns the length of a string.
No. Strings are immutable.
The + operator.
The * operator.
in and not in.
Slicing is retrieving a part of a string using an index range.
for loop and while loop.
2-Mark / Short Answer
Positive indexing starts from 0 at the left side and ends at n-1. Negative indexing starts from -1 at the right side and ends at -n.
A string cannot be changed after it is created. Trying to assign a new value to an individual character produces an error.
| in | not in |
|---|---|
| Returns True when the first string occurs in the second. | Returns True when the first string does not occur in the second. |
str1[n:m] returns characters starting from index n
and ending before index m. The number of characters is m-n.
Start index at 0 and continue while index is less than the string length. Access the character using str1[index] and increment index after each iteration.
Important Programming Questions
- Write a program to count occurrences of a character in a string.
- Write a program to replace vowels with
*. - Write a program to display a string in reverse order.
- Write a function to reverse a string.
- Write a function to check whether a string is palindrome or not.
β‘ Quick Revision
Important Definitions
- String: A sequence of one or more UNICODE characters.
- Indexing: Accessing individual characters using indexes.
- Immutable: A string whose contents cannot be changed after creation.
- Slicing: Accessing a portion of a string using an index range.
- Palindrome: A string that reads the same forwards and backwards.
Important Index Rules
| Rule | Value / Form |
|---|---|
| First positive index | 0 |
| Last positive index | n-1 |
| First negative index | -1 |
| Last negative index | -n |
| Basic slicing | str1[n:m] |
| Slicing with step | str1[n:m:k] |
| Reverse using slicing | str1[::-1] |
Important Operators
| Operator | Purpose |
|---|---|
+ |
Concatenation |
* |
Repetition |
in |
Membership check |
not in |
Reverse membership check |
Important String Methods
len(),
title(),
lower(),
upper(),
count(),
find(),
index(),
endswith(),
startswith(),
isalnum(),
islower(),
isupper(),
isspace(),
istitle(),
lstrip(),
rstrip(),
strip(),
replace(),
join(),
partition(),
split()
Exam-Focused Points
- Remember that string indexing starts from 0.
- Remember negative indexing starts from -1.
- Strings are immutable.
+joins strings.*repeats strings.inandnot inare membership operators.- Slicing uses start, stop and optional step.
str1[n:m]excludes index m.- String traversal can be performed with for and while loops.
- Practice all five textbook programs.
- Pay special attention to string method outputs in programming questions.
π― Final Revision
Before the examination, revise the chapter in this order:
- String definition and creation
- Positive and negative indexing
len()- String immutability
- Concatenation and repetition
- Membership operators
- Slicing and step size
- String traversal using for and while loops
- String methods and built-in functions
- All five textbook programs
- Textbook exercises
- Programming problems
π This article was researched and written by Venkatesh A, Founder of verakworld.com.