Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
220 views

Worksheet class 11 string

Uploaded by

Aniket Dubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views

Worksheet class 11 string

Uploaded by

Aniket Dubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Worksheet: Strings in Python

Section A: MCQs (1 Mark Each)

1. What is the output of the following code?

s = "Python"
print(s[1:4])
a) Pyt b) yth c) tho d) ytho
Answer: b) yth
2. Which of the following methods is used to remove any whitespace from the beginning or
the end of a string?
a) strip() b) split() c) replace() d) find()
Answer: a) strip()

3. What will be the output of the following code?

s = "hello"
print(s.upper())
a) HELLO b) hello c) error d) hELLO
Answer: a) HELLO
4. Which of the following is not a valid string method in Python?
a) upper() b) reverse() c) split() d) join()
Answer: b) reverse()

5. What is the result of the following expression?

"Python" * 2

a) Python2 b) Python Python c) PythonPython d) Error

Answer: c) PythonPython

Section B: Very Short Questions (2 Marks Each)

1. What is a string in Python?


Answer: A string in Python is a sequence of characters enclosed within single quotes (' ')
or double quotes (" "). Strings are immutable, meaning once defined, their contents cannot
be changed.
2. How can you access the last character of a string?
Answer: You can access the last character of a string using negative indexing. For
example, if s = "Python", s[-1] will return "n".
3. Explain the use of the find() method.
Answer: The find() method returns the lowest index of the substring if it is found in the
string. If not, it returns -1. Example: "hello".find("e") will return 1.
4. What does the split() method do in a string?
Answer: The split() method breaks up a string into a list based on a specified delimiter.
By default, the delimiter is whitespace. For example, "Hello World".split() will return
['Hello', 'World'].
5. What is string slicing in Python? Give an example.
Answer: String slicing is a way to extract a part of a string. The syntax is string[start:end],
where start is inclusive and end is exclusive. Example: "Python"[1:4] returns "yth".

Section C: Programming Questions (3 Marks Each)

1. Write a Python program to check if a string is a palindrome.


Answer:

def is_palindrome(s):
s = s.lower()
return s == s[::-1]

# Test the function


string = "Madam"
if is_palindrome(string):
print(f"{string} is a palindrome")
else:
print(f"{string} is not a palindrome")

2. Write a Python program to count the number of vowels in a given string.


Answer:

def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count

# Test the function


string = "Hello World"
print(f"Number of vowels: {count_vowels(string)}")

3. Write a Python program to reverse a given string.


Answer:

def reverse_string(s):
return s[::-1]

# Test the function


string = "Python"
print(f"Reversed string: {reverse_string(string)}")
4. Write a Python program to replace all spaces in a string with an underscore (_).
Answer:

def replace_spaces(s):
return s.replace(" ", "_")

# Test the function


string = "Hello World"
print(f"Modified string: {replace_spaces(string)}")

5. Write a Python program to find the length of a string without using the len()
function.
Answer:

def string_length(s):
count = 0
for char in s:
count += 1
return count

# Test the function


string = "Hello"
print(f"Length of the string: {string_length(string)}")

Worksheet: Strings in Python (Part 2)

Section A: MCQs (1 Mark Each)

1. What will be the output of the following code?

s = "Python Programming"
print(s[::2])

a) Pto rgamn b) Pto rgamnin c) Pto rgamnig d) PthnPormig

Answer: d) PthnPormig

2. Which of the following expressions will return the string "Hello"?


a) ''.join(['H', 'e', 'l', 'l', 'o'])
b) '+'.join(['H', 'e', 'l', 'l', 'o'])
c) '-'.join(['H', 'e', 'l', 'l', 'o'])
d) ' '.join(['H', 'e', 'l', 'l', 'o'])

Answer: a) ''.join(['H', 'e', 'l', 'l', 'o'])

3. What does the rfind() method do?

a) Finds the first occurrence of a substring.


b) Finds the last occurrence of a substring.
c) Replaces all occurrences of a substring.
d) Replaces the first occurrence of a substring.

Answer: b) Finds the last occurrence of a substring.


4. What will be the output of the following code?
s = "hello"
print(s.capitalize())
a) HELLO b) Hello c) hellO d) hello
Answer: b) Hello
5. Which method would you use to check if a string starts with a particular substring?
a) startswith() b) endswith() c) find() d) index()
Answer: a) startswith()

Section B: Very Short Questions (2 Marks Each)

1. What is string immutability?


Answer: String immutability means that once a string is created, it cannot be changed.
Any operation that alters the string creates a new string object instead of modifying the
original one.
2. How do you concatenate two strings in Python?
Answer: Strings can be concatenated using the + operator. For example, "Hello" + "
World" results in "Hello World".
3. Explain the use of the replace() method in strings.
Answer: The replace() method returns a copy of the string where all occurrences of a
substring are replaced with another substring. Example: "apple".replace("a", "o") results in
"opple".
4. How do you find the length of a string in Python?
Answer: The len() function is used to find the length of a string. Example: len("Python")
returns 6.
5. What is the difference between isupper() and upper() in Python?
Answer: The isupper() method checks if all the characters in a string are uppercase and
returns a boolean. The upper() method converts all the characters in a string to uppercase
and returns a new string.

Section C: Programming Questions (3 Marks Each)


1. Write a Python program to remove vowels from a given string.
Answer:
def remove_vowels(s):
vowels = "aeiouAEIOU"
result = ""
for char in s:
if char not in vowels:
result += char
return result
# Test the function
string = "Programming is fun"
print(f"String without vowels: {remove_vowels(string)}")
2. Write a Python program to count the number of occurrences of a substring in a
given string.
Answer:

def count_substring(s, sub):


return s.count(sub)

# Test the function


string = "Hello, Hello, how are you?"
substring = "Hello"
print(f"Occurrences of '{substring}': {count_substring(string, substring)}")

3. Write a Python program to check if a given string starts with a vowel.


Answer:

def starts_with_vowel(s):
vowels = "aeiouAEIOU"
return s[0] in vowels

# Test the function


string = "Apple"
if starts_with_vowel(string):
print(f"{string} starts with a vowel")
else:
print(f"{string} does not start with a vowel")
4. Write a Python program to find the longest word in a given sentence.
Answer:
def longest_word(sentence):
words = sentence.split()
return max(words, key=len)

# Test the function


sentence = "Python programming is interesting"
print(f"Longest word: {longest_word(sentence)}")
5. Write a Python program to convert a given string to title case (each word starts with
a capital letter).
Answer:
def to_title_case(s):
return s.title()

# Test the function


string = "python programming language"
print(f"Title case: {to_title_case(string)}")
Worksheet: Strings in Python (Part 3)

Section A: MCQs (1 Mark Each)

1. What is the output of the following code?

s = "Python"
print(s[-6])

a) n b) P c) y d) h

Answer: b) P

2. Which method is used to return a copy of the string with leading and trailing whitespaces
removed?
a) rstrip() b) strip() c) lstrip() d) replace()
Answer: b) strip()

3. What will be the output of the following code?

s = "abcdef"
print(s.index("e"))

a) 3 b) 4 c) 5 d) Error

Answer: b) 4

4. What is the result of the following expression?

"Python" + "Rocks"

a) PythonRocks b) Python Rocks c) Error d) None of the above

Answer: a) PythonRocks

5. Which of the following will result in a string of all lowercase letters?

a) s.lower() b) s.islower() c) s.upper() d) s.capitalize()

Answer: a) s.lower()

Section B: Very Short Questions (2 Marks Each)

1. How do you check if a string contains only numeric characters?


Answer: You can use the isnumeric() method. If the string contains only numeric
characters, it returns True; otherwise, it returns False.
2. Explain the join() method with an example.
Answer: The join() method is used to join elements of a sequence (like a list or tuple) into
a single string, using a specified separator. Example: "-".join(['a', 'b', 'c']) results in "a-b-c".
3. What is the difference between rindex() and rfind()?
Answer: Both methods return the highest index of the substring if found. The difference is
that rfind() returns -1 if the substring is not found, whereas rindex() raises a ValueError.
4. How do you compare two strings in Python?
Answer: Strings can be compared using comparison operators like ==, !=, <, >, <=, and
>= based on lexicographical order (ASCII values).
5. Explain string formatting using the format() method with an example.
Answer: The format() method allows for variable substitution and formatting. Example:

"{} is {} years old".format("John", 25)

Output: "John is 25 years old"

Section C: Programming Questions (3 Marks Each)

1. Write a Python program to check if two strings are anagrams.


Answer:

python
Copy code
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)

# Test the function


string1 = "listen"
string2 = "silent"
if are_anagrams(string1, string2):
print(f"{string1} and {string2} are anagrams")
else:
print(f"{string1} and {string2} are not anagrams")

2. Write a Python program to remove all special characters from a given string.
Answer:

import re

def remove_special_chars(s):
return re.sub(r'[^A-Za-z0-9 ]+', '', s)

# Test the function


string = "Hello! How@ are# you?"
print(f"String after removing special characters: {remove_special_chars(string)}")
3. Write a Python program to check if a given string is a valid identifier.
Answer:
def is_valid_identifier(s):
return s.isidentifier()

# Test the function


string = "my_variable"
if is_valid_identifier(string):
print(f"'{string}' is a valid identifier")
else:
print(f"'{string}' is not a valid identifier")

4. Write a Python program to print the frequency of each character in a string.


Answer:

def char_frequency(s):
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq

# Test the function


string = "hello world"
frequency = char_frequency(string)
print(f"Character frequencies: {frequency}")

5. Write a Python program to reverse the words in a given sentence.


Answer:

def reverse_words(sentence):
words = sentence.split()
return ' '.join(reversed(words))

# Test the function


sentence = "Python is fun"
print(f"Reversed sentence: {reverse_words(sentence)}")

You might also like