pythonstringreversing

How does the function call to reverse the string in the code below?


def reverse(s): 
  str = "" 
  for i in s: 
    str = i + str
  return str
  
s = "Geeksforgeeks"
  
print ("The original string  is : ",end="") 
print (s) 
  
print ("The reversed string(using loops) is : ",end="") 
print (reverse(s))

I tried the code in my own way to understand how the above method is reversing the string entered in s in my own way

i will post what i tried to know where I have gone wrong in my understanding

s='preetham'
for i in s:
    str=''
    s=i+str
    print(s)

I tried the above code to just understand what role is i and str playing in helping the code to reverse the string, as I predicted from my understanding the above code should print the following output

p
r
e
e
t
h
a
m
*

Solution

  • For the output p r e e t h a m you should use :

    s='preetham'
    str = ''
    for i in s:
        str=str + i + ' '
    print(str)
    

    So, What this does?

    First line we store preetham in a variable s.

    Second we initialize a variable str with ''[an empty string] to store the new string

    Third we start a for loop.
    Here what does the for loop do? The variable i extracts each character[or you may call letter here] of strings one by one and each time executes the code within the loop with each value of i.

    Inside the loop:
    We append each character[stored in i] of to str along with a space [' '].

    Last line outside the loop we print the value of str which is now p r e e t h a m

    So What happens when we run the program?

    First i = 'p' & str = '' str = '' + 'p' + ' ' [ = 'p ']

    Then i = 'r' & str = 'p ' str = 'p ' + 'r' + ' ' [= 'p r ']

    ...

    Finally i = 'm', & str = 'p r e e t h a ' str = 'p r e e t h a ' + 'm' + ' ' [ = 'p r e e t h a m ']

    Lastly in print we print str: p r e e t h a m

    So.

    p
    r
    e
    e
    t
    h
    a
    m
    

    Will be printed if just use '\n' instead of ' '

    Now You can understand the 2 other codes too by this explanation.