Reminder
- It is possible to iterate over strings! No need to split string into lists for that matter. (Unless you have to reverse a text! Example: "I love you" to "you love I"). Related reading: Best way to loop over a python string backwards
Key
- Use of a for loop and
range()
The solution
- Trick is to get index of each string character in reverse fashion then use the indices to slice the string backwards
1
2
3
4
5
6
def reverse(astring):
rev = ''
for i in range(len(astring), 0, -1) # start, end, step
rev += astring[i-1] # add the last character of rev and so on
return rev