1

Is there a simpler way to take a sentence string and return the sentence with the order of the characters in each word reversed? Importantly, the order of the characters in the words is reversed, NOT reverse the order of words in the sentence.

def reverse_words(sent):

    reverseall = sent[::-1]
    reversewordlist = reverseall.split()
    newlist = reversewordlist[::-1]
    newsentence = " ".join(newlist)
    return newsentence


print(reverse_words('keep coding'))                                   # => 'peek gnidoc'
peyo
  • 351
  • 4
  • 15

2 Answers2

1

You pretty much have the idea, but it's possible to pack it in more using a generator expression:

>>> sentence = "stack overflow rules"
>>> " ".join(x[::-1] for x in sentence.split())
'kcats wolfrevo selur'

Passing a single-space string into split allows preservation of consecutive whitespaces, as suggested here:

>>> sentence = "     stack   overflow rules "
>>> " ".join(x[::-1] for x in sentence.split(" "))
'     kcats   wolfrevo selur '
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • If we typed [ return x[::-1] for x in sentence.split() ] without the join function, how come the output isn't an array of the character in the words in reverse? For example: ['kcats', 'wolfrevo', 'selur'] – peyo Sep 23 '19 at 03:25
  • 1
    It should be `return [x[::-1] for x in sentence.split()]`. – ggorlen Sep 23 '19 at 03:26
  • Ah, I see. The square brackets. – peyo Sep 23 '19 at 03:29
  • When something is added in the parentheses in .join, it doesn't have to be defined as an array? – peyo Sep 23 '19 at 03:33
  • 2
    Here's the details on that, I believe the answer is that .join needs an iterator, and since all generators are also iterators, it works. This answer goes into details nicely: https://stackoverflow.com/a/28353158/11547576 – neutrino_logic Sep 23 '19 at 03:40
0
    var a = "urulagneb**ytic***0065"
    var supertemp = "";
    function rever(input) {
        var pattern = /[!@#$%^&*(),.?":{}|<>]/;
        let temp = "";
        for (let a1 = 0; a1 <= input.length; a1++) {
            if (a1 == input.length && temp != "") {
                let tempreg = temp;
                temp = "";
                supertemp = supertemp + tempreg.split("").reverse().join("");
            }
            if (input[a1] != undefined && pattern.test(input[a1])) {
                if (temp != "") {
                    let tempreg = temp;
                    temp = "";
                    supertemp = supertemp + tempreg.split("").reverse().join("") + input[a1];
                }
                else {
                    supertemp = supertemp + input[a1];
                }
            }
            if (input[a1] != undefined && !pattern.test(input[a1])) {
                temp = temp + input[a1];
            }
        }
    }
    rever(a)
    console.log("supertemp", supertemp)
/// output --> bengaluru**city***5600