Home › Python programs (Hindi)
String Reverse Program Python में — code, output और dry run
Problem statement
"python" जैसी string को "nohtyp" बनाना — original string को बदले बिना characters उल्टे क्रम में जोड़ना।Approach 1: simple loop
Walk the string from the last character to the first and collect them one by one. len(s) - 1 is the last position, and the loop counts down to 0.
s = "python"
reversed_text = ""
for i in range(len(s) - 1, -1, -1):
reversed_text = reversed_text + s[i]
print(reversed_text)
# Output: nohtypEach iteration adds one character to the front-runner string. Slow for huge inputs, but it shows exactly what "reversing" means.
Approach 2: reusable function
Put the loop in a function and return the result. A function makes the operation reusable and keeps the original string untouched — the caller stores the returned value.
def reverse_string(text):
result = ""
for ch in text:
result = ch + result # prepend: new char goes in FRONT
return result
print(reverse_string("python")) # nohtyp
print(reverse_string("a")) # a
print(reverse_string("")) # (empty string)This version walks forwards but prepends each character, which reverses just as well — and handles the empty string with no extra code.
Approach 3: Pythonic alternative
Python's slice notation has a built-in step argument, and a step of -1 walks the whole string backwards in one expression — the idiomatic answer.
s = "python"
print(s[::-1]) # nohtyp
print("".join(reversed(s))) # nohtyp — the explicit cousin[::-1] reads "from start to end, stepping backwards". The reversed() + join() form spells the same idea out longhand and is easier to adapt when you need every second character or a partial reverse.
Dry run
"abc" को prepend वाले version में चलाएँ। शुरुआत: result = ""। 'a' के बाद: "a"। 'b' के बाद: "ba" — नया character आगे जुड़ा। 'c' के बाद: "cba"। हर step बस यही है: "एक character, फिर अब तक जुड़ी हुई string"। Slice version में string की positions को दाएँ से बाएँ पढ़ो — 5, 4, 3, 2, 1, 0 — और nohtyp खुद-ब-खुद बन जाता है।Common errors
s.reverse()call करना — string में reverse method होती ही नहीं (list में होती है)।- String को in-place बदलने की कोशिश — strings immutable हैं।
- Countdown loop में
range(len(s), 0, -1)लिखना — पहला character छूट जाएगा। reversed(s)को सीधे print करना — पहलेjoinकरना ज़रूरी है।- Loop में पीछे की बजाय आगे जोड़ना — उल्टी की जगह वही string दोबारा बन जाएगी।
Practice on PyDebug
Concept समझने के बाद इन free problems को browser में solve करें: