Python: String Reversal

Today I’m sharing a simple python program that accepts an input string and reverses it.

def reverse_word(word):
    
    letters = list(word)
    start = 0
    end = len(letters)-1
    
    while start < end:
        letters[start], letters[end] = letters[end], letters[start]
        start+=1
        end-=1
        
    return ''.join(letters)

reverse_word('Nice work') #output: krow eciN

The program starts by accepting a string word, converts it to a list type in letters, sets the start to 0 and end index to length of the input string minus one.

Next a while loop runs from while start and end pointers don’t cross each other. In each iteration, we swap the characters at start and end index and also increment and decrement the start and end pointers respectively.

The end result gets us a reversed version of input string. For example: “Nice work” gets turned into “krow eciN”.

In one of the next posts I’ll write about “sentence” reversal. For example: “Nice work” will be turned into “work Nice”.

Leave a comment