Reverse a String Using a Loop

Easy ⏱ 8 min 78% acceptance ★★★★☆ 4.4
Write a function reverse_string(s) that returns s reversed, built up using a for loop (do not use slicing like s[::-1] or reversed()).

Examples

Example 1
Input
reverse_string("hello")
Output
"olleh"
Explanation

Characters in reverse order.

Example 2
Input
reverse_string("a")
Output
"a"
Explanation

Single character reversed is itself.

Constraints

  • s is a string.
  • Must not use slicing or the built-in reversed() function.

Topics

Loopsfor loop

Companies

GoogleMicrosoft

Hints

Hint 1

Start with an empty result string.

Hint 2

Prepend (or insert at front) each character as you iterate, or iterate the string backward with range.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.