Introduction:
This Python code demonstrates how to reverse a given string using a string reversal function. By inputting a string, you will receive the reversed string as an output. This code is user-friendly and efficient.
Code:
#Function to reverse a string
def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
#end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)
Logic:
- The code defines a function called “reverseString” that takes a string as an argument and returns the reversed string.
- Inside the function, it creates a new empty string. Calculates the length of the input string.
- Uses a for loop to iterate through the input string in reverse order.
- The loop starts from -1 and goes up to -length-1, with a step of -1.
- During each iteration, it appends the current character of the input string to the new string.
- The main code prompts the user to input a string.
- Then, it calls the “reverseString” function with the input string as an argument.
- Stores the returned reversed string in the variable “st1”.
- Finally, it prints the original string and the reversed string as output.
Output:
Enter a String: Hello
>>The original String is: Hello
>>The reversed String is: olleH