Python Revision Tour II — Question 3
Back to all questionshe hello wor ld
w ll
llo wo or
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