Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".
def reverse(inStr): newStr = "" #As we want to use the index operator [] to #pick a character from the original str (inStr) #we want the range to move backwards from the #last character to the first. #The last character in inStr has the index value of len(inStr) -1 #We need -1 as len returns the number of characters found in inStr #but the index starts at 0. #The secons -1 in the range is there because we want to end the range at the value #before -1, that is 0, the index value of the first character in inStr. #The last -1 is so the range will decreese its values by one each time. for i in range(len(inStr)-1,-1,-1): #Append this character into newStr newStr += inStr[i] return newStr def main(): print(reverse("I am testing")) if __name__ == '__main__': main()
Note! There are simpler ways to reverse a string but as this is an easy exercise this solution is sufficient.