Exercise: Reverse a String (Python)
py-reverse-string
Write a function reverse_str that returns the reverse of a string.
reverse.py
๐ก Hints
Hint 1: Slicing
Python slicing supports negative steps. For example: s[::-1].
Hint 2: Built-in reversed
''.join(reversed(s)) returns a reversed string.
โ ๏ธ Try the exercise first! Show Solution
def reverse_str(s: str) -> str:
return s[::-1]
๐งช Tests
Run these tests locally with:
cargo test
View Test Code
import unittest
class TestReverse(unittest.TestCase):
def test_reverse(self):
self.assertEqual(reverse_str("abc"), "cba")
self.assertEqual(reverse_str(""), "")
self.assertEqual(reverse_str("a"), "a")
if __name__ == '__main__':
unittest.main()
๐ค Reflection
- Which approach do you prefer: slicing or reversed()?
- How would you handle non-ASCII strings? (Hint: Python str is Unicode.)