I found this piece of code from a related question about reversing strings in python, but can someone please interpret it in plain English? Please note that I am still new to python and only learnt how to use while loops and functions yesterday :/ so I cant really put this into words myself cause my understanding isn't quite there yet.
anyways here is the code:
def reverse_string(string):
new_strings = []
index = len(string)
while index:
index -= 1
new_strings.append(string[index])
return ''.join(new_strings)
print(reverse_string('hello'))
CodePudding user response:
Surely by knowing what it does, you can figure the code. In the while
loop, the index
value starts from the end of the string and counts down to 0. In each step, it adds that character (again, starting from the end) to the end of the list it is building. Finally, it combines the list into a string.
So, given 'abcd', the list gets built:
'abcd' #3 -> ['d']
'abcd' #2 -> ['d','c']
'abcd' #1 -> ['d','c','b']
'abcd' #0 -> ['d','c','b','a']
CodePudding user response:
Well basically, the get the length of the string with the len
method. Which will return you an integer value representing how long that string is.
They then use the length of this string and effectively iterate down to zero in a while
loop. Using the -=
operator.
Each iteration (meaning each time around the loop) it will take away from length until it reaches zero.
So lets use hello
as an example input and go through this together.
reverse_string('hello')
is how we would call the method, done in the print
statement of your code.
We then enter the function and perform these steps:
- We create a new empty array called
new_strings
. - We find the length of the initial string
hello
which returns us 5. Meaning that nowindex
is equal to 5. - We create a while loop that keeps on going until
index
is no more usingwhile(index):
- a while loop like this treats a0
value asfalsy
and will terminate upon reaching this. Therefore whenindex
is0
the loop will stop. - The first line of this loop performs
index -= 1
which is the same as writingindex = index - 1
so the very first loop through we getindex = 5 - 1
and then nowindex
is equal to4
. - Because Python then lets us access the
character
of a string usingstring[index]
(and because this works from 0 -> n) performinghello[4]
will in fact give us the charactero
. - We also append this character to the array
new_strings
meaning that as we go through the iterations to reach zero it will add each character backwards to this array giving us['o', 'l', 'l', 'e', 'h']
- Since index is now zero we leave the loop and perform a
join
operation on the array to yet again create a string. The command''.join(new_strings)
means that we wish to join the array we previously had without a separator. If we had done'#'.join(new_strings)
we instead would have gotteno#l#l#e#h
instead ofolleh
.
I hope this answer gives you some clarity.
CodePudding user response:
Sure, It is very simple program. You should reffer string methods and string indexing in python to get clear idea. Let me explain this in deatial.
print(reverse_string('hello'))//The print function is calling another function reverse_string and passing argument"hello".
def reverse_string(string):// The argument "hello" is stored in the variable string in reverse_string function.
**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument
passed to the function. len("hello")=5 and assigned
to index. index=5.
while index: // while loop exicute until the condition get false .In this example when index =0.in string the indexing start from 0 .For example. string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o.
**index -= 1** //Note the last letter 'o' is in string[4] and the len
function returned 5 so we need to decrement index variable
to 4 so that it will pointing to string[4]=o
new_strings.append(string[index]) // append string[4] that is o and so on ... return ''.join(new_strings)