Q.Program 8-4: Write a program which reverses a string passed as parameter and stores the reversed string in a new string. Use a user defined function for reversing the string.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Same backward walk as Program 8-3, but now each character is APPENDED to a new string inside a user-defined function, and that reversed string is returned to the caller.
Idea. This program contrasts with Program 8-3: there we merely printed in reverse; here the reversed text must be stored in a new string. The function takes the string as a parameter, iterates the negative indices -1 down to -len(st), concatenates each character onto newStr, and returns the result — the original string stays intact (strings are immutable anyway).
def reverseString(st):
"""Return a new string that is the reverse of st."""
newStr = ''
length = len(st)
for i in range(-1, -length - 1, -1): # -1, -2, ..., -length
newStr += st[i]
return newStr
# main program
st = input("Enter a string: ")
st1 = reverseString(st)
print("The original string is:", st)
print("The reversed string is:", st1)
Key lines:
range(-1, -length - 1, -1)— produces -1, -2, …, -length: last character first, first character last.newStr += st[i]— the accumulation step; this is what builds the new reversed string (the difference from Program 8-3).return newStr— the reversed string travels back to the caller and lands in st1.
Trace for st = "Python" (length 6):
| i | st[i] | newStr |
|---|-------|--------| …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.