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

Write a function reverseString(STR) in Python, that takes a string - Sample Paper 2 by Teachoo

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:

part 2 - Question 21 (Choice 1) - Sample Paper 2 by Teachoo - Teachoo Sample Paper - Computer Science - Class 11

-endlock-

Remove Ads
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.