Strings - Class 11 Computer Science - Chapter 8 - Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubt-solving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes - Strings | Class 11 NCERT | Computer Science
Comprehensive Strings Class 11 Notes: Understanding Python Strings
Introduction
Definition of Strings
A string in Python is a sequence composed of one or more Unicode characters. These characters can include letters, digits, whitespace, or symbols. Strings are essential in any programming language as they allow us to work with text data.
Types of Quotes for Strings in Python
Python allows strings to be created using different types of quotes:
Single quotes:
'Hello World!'
Double quotes:
"Hello World!"
Triple quotes:
'''Hello World!'''
or"""Hello World!"""
Accessing Characters in a String
String Indexing
String indexing enables accessing individual characters within a string. Python supports both positive and negative indexing.
Positive Indexing
The positive index starts from 0 for the first character to (n-1) for the last character, where (n) is the length of the string.
str1 = 'Hello World!'
print(str1[0]) # 'H'
print(str1[6]) # 'W'
print(str1[len(str1)-1]) # '!'
Negative Indexing
Negative indexing starts from -1 for the last character to (-n) for the first character.
print(str1[-1]) # '!'
print(str1[-12]) # 'H'
Index Errors
If you try to access an index outside the valid range, you'll encounter an IndexError
.
print(str1[15]) # IndexError: string index out of range
Immutability of Strings
Strings in Python are immutable, meaning their contents cannot be changed after creation. Any attempt to modify a string results in an error.
str1 = "Hello World!"
str1[1] = 'a' # TypeError: 'str' object does not support item assignment
String Operations
Concatenation
Concatenation refers to joining two strings using the +
operator.
str1 = 'Hello'
str2 = 'World!'
print(str1 + str2) # 'HelloWorld!'
Repetition
You can repeat a string using the *
operator.
str1 = 'Hello'
print(str1 * 2) # 'HelloHello'
print(str1 * 5) # 'HelloHelloHelloHelloHello'
Membership Operators
Python's membership operators, in
and not in
, check for substrings within strings.
str1 = 'Hello World!'
print('W' in str1) # True
print('My' not in str1) # True
Slicing Strings
Slicing allows you to access a portion of a string by specifying a range.
str1 = 'Hello World!'
print(str1[1:5]) # 'ello'
print(str1[7:10]) # 'orl'
Advanced slicing includes a step parameter to skip characters.
print(str1[0:10:2]) # 'HloWr'
print(str1[::-1]) # '!dlroW olleH' (reversed string)
String slicing:
graph TD
A[Original String] --> B[H e l l o W o r l d!]
B --> C["Slicing (str1[1:5])"]
C --> D[ello]
B --> E["Slicing with step (str1[0:10:2])"]
E --> F[HloWr]
B --> G["Reversed (str1[::-1])"]
G --> H[!dlroW olleH]
Traversing a String
Using For Loop
str1 = 'Hello World!'
for ch in str1:
print(ch, end='')
### Output: Hello World!
Using While Loop
index = 0
while index < len(str1):
print(str1[index], end='')
index += 1
### Output: Hello World!
Built-in String Functions
Common Methods
len()
: Returns the length of the string.upper()
: Converts all characters to uppercase.lower()
: Converts all characters to lowercase.title()
: Capitalises the first letter of every word.count(substr)
: Counts occurrences of a substring.find(substr)
: Returns the first index of a substring.replace(old, new)
: Replaces all occurrences of the old string with the new string.split()
: Splits a string into a list based on a delimiter.join()
: Joins list elements into a string with a separator.
Handling Strings with Custom Functions
Counting Character Occurrences
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
print(f"Number of times character {ch} occurs in the string is: {charCount(ch, st)}")
Replacing Vowels
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
print(f"The modified String is: {replaceVowel(st)}")
Reversing a String
def reverseString(st):
newstr = ''
for i in range(len(st)-1, -1, -1):
newstr += st[i]
return newstr
st = input("Enter a String: ")
print(f"The reversed String is: {reverseString(st)}")
Checking for Palindromes
def checkPalin(st):
return st == st[::-1]
st = input("Enter a String: ")
if checkPalin(st):
print(f"The given string {st} is a palindrome")
else:
print(f"The given string {st} is not a palindrome")
Examples and Exercises
Practical Examples
Let's consider some practical examples and exercises to strengthen your understanding of strings in Python.
mySubject = "Computer Science"
print(mySubject[0:len(mySubject)]) # 'Computer Science'
print(mySubject[-7:-1]) # 'Scienc'
print(mySubject[::2]) # 'Cmue cine'
print(mySubject[len(mySubject)-1]) # 'e'
print(2*mySubject) # 'Computer ScienceComputer Science'
print(mySubject[::-2]) # 'ecneicpC'
print(mySubject[:3] + mySubject[3:]) # 'Computer Science'
print(mySubject.swapcase()) # 'cOMPUTER sCIENCE'
print(mySubject.startswith('Comp')) # True
print(mySubject.isalpha()) # False
Exercises for Practice
Try these exercises to test your skills:
Write a program to count characters, alphabets, digits, special characters, and words in a text.
Convert a multi-word string to title case.
Delete all occurrences of a specified character from a string.
Sum up digits present in a string.
Replace each space with a hyphen in a sentence.
Conclusion
Strings are a fundamental data type in Python. This comprehensive guide provided you with an understanding of defining, manipulating, and handling strings using various methods and custom functions. Practice the provided exercises to gain proficiency in working with strings.
🚀 Learn more about Notes with Chatterbot AI
Extra Questions - Strings | NCERT | Computer Science | Class 11
💡 Have more questions?
Ask Chatterbot AINCERT Solutions - Strings | NCERT | Computer Science | Class 11
Consider the following string mySubject
:
mySubject = "Computer Science"
What will be the output of the following string operations :
i. print(mySubject[0:len(mySubject)])
ii. print(mySubject[-7:-1])
iii. print(mySubject[::2])
iv. print(mySubject[len(mySubject)-1])
v. print(2*mySubject)
vi. print(mySubject[::-2])
vii. print(mySubject[:3] + mySubject[3:])
viii. print(mySubject.swapcase())
ix. print(mySubject.startswith('Comp'))
x. print(mySubject.isalpha())
i. print(mySubject[0:len(mySubject)])
This operation slices the string from the start to the end.
Output: Computer Science
ii. print(mySubject[-7:-1])
This operation slices the string from the 7th last character to the 2nd last character (both inclusive).
Output: Scienc
iii. print(mySubject[::2])
This operation slices the string with a step size of 2, meaning it takes every second character.
Output: Cmue cec
iv. print(mySubject[len(mySubject)-1])
This operation prints the last character of the string (len(mySubject)-1
equals the index of the last character).
Output: e
v. print(2*mySubject)
This operation prints the string twice.
Output: Computer ScienceComputer Science
vi. print(mySubject[::-2])
This operation slices the string in reverse order with a step size of 2.
Output: ecneScp
vii. print(mySubject[:3] + mySubject[3:])
This operation concatenates the slices of the string from start to index 3 and from index 3 to the end. Essentially, it's the whole string.
Output: Computer Science
viii. print(mySubject.swapcase())
This operation swaps the case of each character in the string.
Output: cOMPUTER sCIENCE
ix. print(mySubject.startswith('Comp'))
This operation checks if the string starts with "Comp".
Output: True
x. print(mySubject.isalpha())
This operation checks if all characters in the string are alphabetic (it will return False
because the string contains a space).
Output: False
Consider the following string myAddress
:
myAddress = "WZ-1,New Ganga Nagar,New Delhi"
What will be the output of following string operations :
i. print(myAddress.lower())
ii. print(myAddress.upper())
iii. print(myAddress.count('New'))
iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New'))
vi. print(myAddress.split(','))
vii. print(myAddress.split(' '))
viii. print(myAddress.replace('New','Old'))
ix. print(myAddress.partition(','))
x. print(myAddress.index('Agra'))
Here are the outputs for each of the string operations:
Converting the string to lowercase:
print(myAddress.lower()) Output: wz-1,new ganga nagar,new delhi
Converting the string to uppercase:
print(myAddress.upper()) Output: WZ-1,NEW GANGA NAGAR,NEW DELHI
Counting the number of times 'New' appears in the string:
print(myAddress.count('New')) Output: 2
Finding the first occurrence of 'New':
print(myAddress.find('New')) Output: 5
Finding the last occurrence of 'New':
print(myAddress.rfind('New')) Output: 20
Splitting the string by commas:
print(myAddress.split(',')) Output: ['WZ-1', 'New Ganga Nagar', 'New Delhi']
Splitting the string by spaces:
print(myAddress.split(' ')) Output: ['WZ-1,New', 'Ganga', 'Nagar,New', 'Delhi']
Replacing 'New' with 'Old':
print(myAddress.replace('New', 'Old')) Output: WZ-1,Old Ganga Nagar,Old Delhi
Partitioning the string at the first comma:
print(myAddress.partition(',')) Output: ('WZ-1', ',', 'New Ganga Nagar,New Delhi')
Finding the index of 'Agra':
print(myAddress.index('Agra')) Output: ValueError: substring not found
For the last operation (
print(myAddress.index('Agra'))
), it will throw aValueError
since 'Agra' does not exist in the stringmyAddress
.
Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), total number of alphabets, total number of digits, total number of special symbols and total number of words in the given text. (Assume that each word is separated by one space).
def count_text_details():
# Initialize counts
total_characters = 0
total_alphabets = 0
total_digits = 0
total_special_symbols = 0
# Input lines of text from user
print("Enter lines of text (Press Enter twice to end):")
lines = []
while True:
line = input()
if line == "":
break
lines.append(line)
# Join all lines into a single text
full_text = ' '.join(lines)
# Calculate total characters including white spaces
total_characters = len(full_text)
# Iterate through the full text to count alphabets, digits and special symbols
for char in full_text:
if char.isalpha():
total_alphabets += 1
elif char.isdigit():
total_digits += 1
elif not char.isspace():
total_special_symbols += 1
# Count total number of words
total_words = len(full_text.split())
# Print the results
print("Total number of characters (including white spaces):", total_characters)
print("Total number of alphabets:", total_alphabets)
print("Total number of digits:", total_digits)
print("Total number of special symbols:", total_special_symbols)
print("Total number of words:", total_words)
# Run the function
count_text_details()
Explanation:
The program keeps reading lines of text from the user until an empty line (pressing Enter twice) is entered.
The
full_text
variable stores the complete input as a single string.Using various Python string methods, the program counts the total characters, alphabets, digits, special symbols, and words.
Finally, it outputs the counts to the user.
Write a user defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised)
Here's a user-defined function that converts a string with more than one word into title case:
def to_title_case(string):
# Split the string into words
words = string.split()
# Capitalize the first letter of each word
title_case_words = [word.capitalize() for word in words]
# Join the words back into a single string
title_case_string = ' '.join(title_case_words)
return title_case_string
# Example usage
input_str = "hello world, this is a test"
title_case_str = to_title_case(input_str)
print("Original String:", input_str)
print("Title Case String:", title_case_str)
Output:
Original String: hello world, this is a test
Title Case String: Hello World, This Is A Test
Explanation:
The function uses the
split()
method to break the string into words.It then uses a list comprehension to capitalize the first letter of each word using the
capitalize()
method.Finally, it uses the
join()
method to combine the words back into a single string with spaces between them.
Write a function deleteChar() which takes two parameters one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.
Below is the implementation of the deleteChar()
function:
def deleteChar(s, ch):
"""
Function to delete all occurrences of `ch` from the string `s`.
Parameters:
s (str): The input string.
ch (str): The character to be deleted.
Returns:
str: The string after deleting all occurrences of `ch`.
"""
new_str = ""
for character in s:
if character != ch:
new_str += character
return new_str
# Example usage
s = "Hello World!"
ch = 'o'
result = deleteChar(s, ch)
print("Original String:", s)
print("Modified String:", result)
Example output:
Original String: Hello World!
Modified String: Hell Wrld!
Explanation:
The function deleteChar() takes two parameters:
s
(the string) andch
(the character to remove).It iterates over each character in the string
s
.If the character is not equal to
ch
, it appends it tonew_str
.Finally, it returns the
new_str
, which is the modified string without occurrences ofch
.
Input a string having some digits. Write a function to return the sum of digits present in this string.
Here is a Python function to sum the digits present in a given string:
def sum_of_digits(s):
total = 0
for char in s:
if char.isdigit():
total += int(char)
return total
# Example usage
s = input("Enter a string: ")
result = sum_of_digits(s)
print("The sum of digits in the string is:", result)
This function works as follows:
Initialize a total sum to 0.
Iterate through each character in the string.
Check if the character is a digit using the
isdigit()
method.If it is a digit, convert it to an integer and add it to the total sum.
Finally, return the total sum.
Example:
Input:
Hello123
Output:
6
(since 1 + 2 + 3 = 6)
Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.
def replace_blanks_with_hyphens(sentence):
"""
Replaces each blank space in the input sentence with a hyphen.
Parameters:
sentence (str): The input sentence where spaces need to be replaced by hyphens.
Returns:
str: The modified sentence with spaces replaced by hyphens.
"""
return sentence.replace(' ', '-')
# Example usage
sentence = "This is a sample sentence"
modified_sentence = replace_blanks_with_hyphens(sentence)
print("Original sentence:", sentence)
print("Modified sentence:", modified_sentence)
Output:
Original sentence: This is a sample sentence
Modified sentence: This-is-a-sample-sentence
Explanation:
Function Name:
replace_blanks_with_hyphens
Parameter: Takes a single parameter
sentence
, which is a string.Return Value: Returns the modified string where each blank space is replaced with a hyphen.
Implementation: Uses the
replace
method of the string to replace all occurrences of a space (' '
) with a hyphen ('-'
).
💡 Have more questions?
Ask Chatterbot AI