str = ‘Amit Upadhyay’
Approach 1:
print str[::-1]
Approach 2:
"".join(reversed(str))
It requires calling a string method str.join
on another called function, which canbe rather slow.
Approach 3:
def reverseString (str):
newStr = ""
index = len(str)
while index:
index -= 1
newStr += str[index]
return newStr;
print reverseString("Amit Upadhyay")
This is bad because strings are immutable. So every time you are appending a new character, which is creating a new string. So it is better to collect your substring in a list and join them later. This moves us to the approach 4.
Approach 4:
def reverseString (str):
newList = []
index = len(str)
while index:
index -= 1
newList.append(str[index])
return "".join(newList);
print reverseString("Amit Upadhyay")
Thank you 👏