Thursday, September 21, 2023
HomeSoftware EngineeringMethods to Reverse Phrases or Sentences in Python

Methods to Reverse Phrases or Sentences in Python

Let’s take the next sentence:

phrases = "These are some phrases"

We are able to use slices to reverse the order of the string:

print( phrases[::-1] )
#sdrow emos period esehT

Let’s say we wished to reverse every phrase within the sentence, however preserve the order of phrases.

We are able to as soon as once more use slices, however we’ll praise it with a checklist comprehension:

print( " ".be a part of([word[::-1] for phrase in phrases.break up(" ")]) )
#esehT period emos sdrow

Methods to Reverse phrases with out utilizing inbuilt modules

Let’s take this a bit additional. Let’s say that we weren’t allowed to make use of our cool new slice toy, how might we reverse a string?

phrases = "These are some phrases"

out = ""
for i in vary(len(phrases)-1, -1, -1):
  out += phrases[i]

#sdrow emos period esehT

As we are able to see, this is identical as doing phrases[::-1], which reveals the facility and ease of slices!

We created a variable to carry our new string, then created a loop, counting from the final merchandise within the index, to 0. We additionally made positive to do that in reverse.

In every iteration, we appended to our output string.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments