Here is a simple function that takes a string as an argument and returns the reversed string:
def reverse_string(string): # Initialize an empty string reversed_string = "" # Iterate over the string in reverse order for i in range(len(string)-1, -1, -1): # Append each character to the reversed string reversed_string += string[i] # Return the reversed string return reversed_string print(reverse_string("hello")) # Output: "olleh" print(reverse_string("world")) # Output: "dlrow" print(reverse_string("python")) # Output: "nohtyp"
This function uses a for loop to iterate over the string in reverse order and appends each character to a new string. The reversed string is then returned.
Alternatively, you could use the join() and slicing method to reverse the string:
def reverse_string(string): return "".join(string[i] for i in range(len(string)-1, -1, -1)) print(reverse_string("hello")) # Output: "olleh" print(reverse_string("world")) # Output: "dlrow" print(reverse_string("python")) # Output: "nohtyp"
This method uses a list comprehension to iterate over the string in reverse order and creates a new string by joining each character. The reversed string is then returned.
You can use either of these methods to reverse a string in Python. Choose the one that best suits your needs and use it in your code.