Introduction

replace() is the temporary replacement of the "method" of the string return type, whereas reverse() is the inversion of the list permanent system type.

Suppose we have the following code in Python:

words = input()  # Receive user input
for i in words:
    if '0' <= i <= '9':
        continue
    else:
        print(words.replace(i,''))
print(words)

If we input "Hello_2022", we will not get "2022", but in fact replace() is a return method (which is temporary), so the whole loop will not change the value of words, and the output will still be "Hello_2022".

The fix

If we want to fix this bug to get a substitute value, Var assignment can be used. It should be noted that Null (empty) is also a valid "character", otherwise the above operation may cause some issue.

words = words.replace(i,'')

It might be a bit hard to understand, but in fact the 'for' operation itself may be more interesting; because in Python, there is the concept of 'iteration'.

reverse()

reverse() is used to reverse combined data types, for example lists, but sadly strings don't have this property (since strings can not be modified after value being assigned). But strings can be reversed by relying on the classic "slicing operation", [::]:

words = input()  # Receive user input
words = words[::-1] # Use the double ':', not single ':'
print(words)
listed = [1, 2, 3]
listed.reverse()
print(listed)
We are all in the gutter, but some of us are looking at the stars.
Last updated on 2022-01-11