Sunday, April 14, 2024
HomeSoftware EngineeringThe way to Reversing Phrases in a String in Python

The way to Reversing Phrases in a String in Python

The problem

Write a perform that reverses the phrases in a given string. A phrase also can match an empty string. If this isn’t clear sufficient, listed below are some examples:

Because the enter could have trailing areas, additionally, you will must ignore pointless whitespace.

Instance (Enter –> Output)

"Good day World" --> "World Good day"
"Hello There." --> "There. Hello"

The answer in Python code

Choice 1:

import re

def reverse(st):
    return " ".be a part of(re.sub('s+', ' ', st).strip().cut up(" ")[::-1])

Choice 2:

def reverse(st):
    return " ".be a part of(reversed(st.cut up())).strip()

Choice 3:

def reverse(st):
    s = st.cut up()
    return ' '.be a part of(s[::-1])

Choice 4:

def reverse(st):
    st = st.cut up()
    return ' '.be a part of(st)

Check circumstances to validate our resolution

import take a look at
from resolution import reverse

@take a look at.describe("Mounted Exams")
def fixed_tests():
    @take a look'Fundamental Check Circumstances')
    def basic_test_cases():
        take a look at.assert_equals(reverse('Good day World'), 'World Good day')
        take a look at.assert_equals(reverse('Hello There.'), 'There. Hello')


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments