How to Reverse Words or Sentences in Python

0 min read 191 words

Let’s take the following sentence:

words = "These are some words"

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

print( words[::-1] )
#sdrow emos era esehT

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

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

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.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags