Python string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
reverse("hello")
# 'olleh'
Answer from akuiper on Stack OverflowPython string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
reverse("hello")
# 'olleh'
The problem is that you can't use del on a string in python.
However this code works without del and will hopefully do the trick:
def reverse(text):
a = ""
for i in range(1, len(text) + 1):
a += text[len(text) - i]
return a
print(reverse("Hello World!")) # prints: !dlroW olleH
iterate over a string in reverse
7 proven methods to reverse the python string in 2021
Videos
I want to iterate over a string in reverse. I googled it and found this way
for i in range(len(k)-1, 0-1, -1):
but to be honest I don't understand it. can you please explain it to me?
also, I would love it if you guys can suggest other methods
Your function will not work since it's not returning the list.
Here is one way to solve this problem - using the for-loop:
def reverse_list(arr):
result = []
for i, _ in enumerate(arr): # try to use enumerate - it's better in most cases
result.append(arr[~i]) # use the backward indexing here
return result
With a list comprehension together with the reversed build-in function (it returns a generator):
def reverse_list(lst):
return [v for v in reversed(lst)]
# or return list(reversed(lst))
Another version but without for-loop to highlight the underlying processes:
Using build-in function slice to select a range of items in a sequence object
and select an element from the container with __getitem__ subscription.
def reverse_list(lst):
# slice object
s = slice(None, None, -1)
# selection
return lst.__getitem__(s) # <--> lst[s]