How to Reverse Words or Sentences in Python
Let’s take the following sentence:
|
|
We can use slices
to reverse the order of the string:
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
:
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?
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.