-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforrevstring.py
More file actions
34 lines (27 loc) · 991 Bytes
/
forrevstring.py
File metadata and controls
34 lines (27 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# reverse a given string
s=input('enter a string: ') # s = 'hai'
rev=''
for ele in range(-1,-(len(s)+1),-1):
rev+=s[ele]
print(rev)
'''Step 1: Initialization
s = "hai" (original string)
rev = "" (empty string to store the reversed result)
Step 2: Set up the for loop
for ele in range(-1, -(len(s)+1), -1):
len(s) = 3 for "hai"
The range becomes range(-1, -4, -1), which means ele will iterate over [-1, -2, -3]
Step 3: Loop Iteration 1 (ele = -1)
s[ele] is s[-1] which is the last character of s, 'i'
rev = rev + s[ele] => "" + "i" = "i"
Step 4: Loop Iteration 2 (ele = -2)
s[ele] is s[-2] which is the second last character of s, 'a'
rev = rev + s[ele] => "i" + "a" = "ia"
Step 5: Loop Iteration 3 (ele = -3)
s[ele] is s[-3] which is the first character of s, 'h'
rev = rev + s[ele] => "ia" + "h" = "iah"
Step 6: End of loop
The loop completes after processing all indices -1, -2, -3
The reversed string stored in rev is "iah"
Step 7: Print the result
print(rev) outputs: iah'''