What will be the output of the following code:
s = "Hello World"
s = s[::-1]
s = s.title()
s = s.replace("l", "*")
print(s)
-
D*roW O**eh
-
DlroW OlleH
-
droW o**eh
-
Dlrow Olleh
Answer:
Answer by student
a. D*roW O**eh
Detailed answer by teachoo
-lock-
The code is written in Python and uses some string methods and slicing techniques. Let’s look at each of the options and see why they are correct or incorrect.
- a. D*roW O**eh : This is the correct option, as it matches the final value of s after applying all the string operations.
- b. DlroW OlleH : This is incorrect , as it does not replace the letter “l” with “*”.
- c. droW o**eh : This is incorrect , as it does not capitalize the first letter of each word.
- d. Dlrow Olleh : This is incorrect , as it does not reverse the string or replace the letter “l” with “*”.
To get the correct answer, we need to follow these steps:
- Reverse the string s by using a negative step of -1. The syntax for slicing is
s[start:stop:step]
-
- where start is the starting index
- stop is the ending index (not included)
- step is the increment or decrement between each index.
- By leaving out the start and stop, we are slicing the whole string, but by using -1 as the step, we are going backwards . So, s becomes “dlroW olleH” .
- Capitalize the first letter of each word in the string s and make the rest lowercase. The title() method does this automatically. So, s becomes “Dlrow Olleh”.
- Replace all occurrences of the letter “l” in the string s with the symbol “ ". The replace(old, new) method takes two arguments: the old substring to be replaced and the new substring to replace it with. So, s becomes "D roW O**eh” .
- Print the final value of s to the output.
So, the correct answer is a. D*roW O**eh
-endlock-