-1

How does the range function reverse the string? I understand that range can intake a: start, stop, step - form. I am trying to understand the way it can reverse the string using the negative integers.

Thank you!

def reverse_string1(a_string):
    result = ''
    for index in range(len(a_string)-1, - 1, -1):
        result += a_string[index]

    return result
    
string_practice = 'Lucky Doggo!'
print(reverse_string1(string_practice))
mhhabib
  • 2,975
  • 1
  • 15
  • 29
  • 4
    Why not write down few iterations of the for loop and track what each variable value is (index and result). I think if you know what range and len does then understanding the rest should be easy! Btw, not a very efficient way to reverse a string ... (read on string immutability) – urban Feb 21 '21 at 09:39
  • 1
    Hi. A classic python example is a_string[::-1] to achieve a string reversal. Check out this post https://stackoverflow.com/questions/13365424/what-does-result-1-mean – JohnnieL Feb 21 '21 at 09:43
  • @urban Hi m8, what's the best way to reverse a string, I'm trying to learn as best I can. – akhelliuz Feb 21 '21 at 09:48
  • @akhelliuz see above the slice [::-1] – JohnnieL Feb 21 '21 at 09:51

1 Answers1

0

For a string of length n, the index of the last character is given by n - 1. This adds characters from a_string to result in the order n - 1, n - 2, ... all the way until 0 (the first character of a_string), therefore reversing the order.

This can be seen in the arguments of the range: start: n - 1, end: -1 (stops when it reaches -1), step: -1 (go backwards).

EDIT: There are also several other simpler ways to reverse strings in python, such as: result = "".join(reversed(a_string)) or result = a_string[::-1]

  • 1
    Thank you for the explanation, this makes a lot of sense. I'm currently trying to learn as best I can. – akhelliuz Feb 21 '21 at 09:49