How to Reverse a String in Python

To reverse a string in Python:

string_example = "Hello World"

reversed_string = string_example[::-1]

print(reversed_string)

The result:

dlroW olleH

Function to reverse a string

Here is a function to reverse a string in Python:

def reverse_string(my_string: str) -> str:
"""
Reverse a string
:param my_string: The string you wish to reverse.
:return: The reversed string
"
""
return my_string[::-1]


string_example = "Hello World"

print(reverse_string(string_example))

The result:

dlroW olleH

Add a Pytest test

To test the “reverse_string” function using Pytest:

import pytest

# Assuming the reverse_string function is stored under app.string_operations
from app.string_operations import reverse_string


@pytest.mark.parametrize("input_string, expected_output", [
("hello", "olleh"),
("12345", "54321"),
("a", "a"),
("", "")
])
def test_reverse_string(input_string, expected_output):
"""
Test the reverse_string function across various input strings.

:param input_string: The input string to be reversed.
:param expected_output: The expected output after reversing the input string.
"
""
assert reverse_string(input_string) == expected_output

The result:

============================= test session starts =============================
collecting ... collected 4 items

test_string_operations.py::test_reverse_string[hello-olleh] PASSED [ '25%']
test_string_operations.py::test_reverse_string[12345-54321] PASSED [ '50%']
test_string_operations.py::test_reverse_string[a-a] PASSED [ '75%']
test_string_operations.py::test_reverse_string[-] PASSED ['100%']

============================== 4 passed in '0.01s' ==============================

Additional Exercises

Leave a Comment