CBSE Class 11 Computer Science Question 10 of 19

Strings in Python — Question 7

Back to all questions
7
Question

Question 6

Find the output of the following:

word = 'work hard'
result = word.find('work')
print("Substring, 'work', found at index:", result)
result = word.find('har') 
print("Substring, 'har ' ,found at index:", result)
if (word.find('pawan') != -1):
    print("Contains given substring ")
else: 
    print("Doesn't contain given substring")
Answer
Output
Substring, 'work', found at index: 0
Substring, 'har ' ,found at index: 5
Doesn't contain given substring
Explanation

The code first searches for the substring 'work' in 'work hard' using find(), which is located at index 0, so it prints "Substring, 'work', found at index: 0". Next, it searches for 'har', which starts at index 5, resulting in "Substring, 'har ', found at index: 5". Finally, it checks if 'pawan' is in the string; since it is not, find() returns -1, and the code prints "Doesn't contain given substring".