CBSE Class 12 Computer Science Question 8 of 22

Python Revision Tour II — Question 3

Back to all questions
3
Question

Question 1(c)

What will be the output produced by following code fragments ?

x = "hello world"  
print(x[:2], x[:-2], x[-2:])  
print(x[6], x[2:4])  
print(x[2:-3], x[-4:-2])  
Answer
Output
he hello wor ld
w ll
llo wo or
Explanation

print(x[:2], x[:-2], x[-2:])
x[:2] extracts the substring from the beginning of x up to index 1, resulting in "he".
x[:-2] extracts the substring from the beginning of x up to the third last character, resulting in "hello wor".
x[-2:] extracts the substring from the last two characters of x until the end, resulting in "ld".
Hence, output of this line becomes he hello wor ld

print(x[6], x[2:4])
x[6] retrieves the character at index 6, which is 'w'.
x[2:4] extracts the substring from index 2 up to index 3, resulting in "ll".
Hence, output of this line becomes w ll

print(x[2:-3], x[-4:-2])
x[2:-3] extracts the substring from index 2 up to the fourth last character, resulting in "llo wo".
x[-4:-2] extracts the substring from the fourth last character to the third last character, resulting in "or".
Hence, output of this line becomes llo wo or

Get the Bright Tutorials app Stuck on a question? Ask Bright Buddy — your AI tutor — for step-by-step help in the app.