Write a function reverseString(STR) in Python, that takes a string, STR as an argument and returns the string with its characters in reverse order. If the string is empty, return an empty string.
For example, Consider the following string
STR = "Hello World"
The output should be:
dlroW olleH
Answer:
Answer by student
Detailed answer by teachoo
-lock-
To write a function that reverses a string, we need to follow these steps:
- Define a function named reverseString that takes a parameter STR , which is the string to be reversed.
- Inside the function, create a variable named reversed and assign it an empty string. This variable will store the reversed string as we build it.
- Use a for loop to iterate over the characters of STR from the end to the beginning. We can use the range function with three arguments: start, stop and step. The start argument is len(STR)-1, which is the index of the last character of STR. The stop argument is -1, which means we want to loop until we reach the index before 0. The step argument is -1, which means we want to decrement the index by 1 in each iteration.
- In each iteration, append the current character to the reversed string using the += operator. This will add the character at the end of the reversed string.
- After the loop ends, return the reversed string as the output of the function.
The final code is:
-endlock-