Skip to content

How to Reverse Words or Sentences in Python

Let’s take the following sentence:

words = "These are some words"
Code language: Python (python)

We can use slices to reverse the order of the string:

print( words[::-1] ) #sdrow emos era esehT
Code language: Python (python)

Let’s say we wanted to reverse each word in the sentence, but keep the order of words.

We can once again use slices, but we will compliment it with a list comprehension:

print( " ".join([word[::-1] for word in words.split(" ")]) ) #esehT era emos sdrow
Code language: Python (python)

How to Reverse words without using inbuilt modules

Let’s take this a bit further. Let’s say that we were not allowed to use our cool new slice toy, how could we reverse a string?

words = "These are some words" out = "" for i in range(len(words)-1, -1, -1): out += words[i] print(out) #sdrow emos era esehT
Code language: Python (python)

As we can see, this is the same as doing words[::-1], which shows the power and simplicity of slices!

We created a variable to hold our new string, then created a loop, counting from the last item in the index, to 0. We also made sure to do this in reverse.

In each iteration, we appended to our output string.

See also  SELECT Duplicate Items Using SQL
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x