【每日一题0819】反转单词

:woman_mage:给定一个字符串,请编写一个python函数,将其中的每个单词的字母顺序进行反转。空格的个数不定,记得需要保留所有的空格哟。

示例:
输入:"Welcome to hogwarts!" ,输出:emocleW ot !strawgoh
输入:"hello world" ,输出:olleh dlrow

题目难度:简单
题目来源:codewars

def reverse_words(text):
    pass

assert reverse_words("Welcome to hogwarts!") == "emocleW ot !strawgoh"
assert reverse_words("hello   world") == "olleh   dlrow"
assert reverse_words("apple") == "elppa"
def reverse_words(text):
    l = text.split(" ")
    result = []
    for i in l:
        result.append(i[::-1])

    return " ".join(result)

def reverse_words(text):
    return " ".join([lis[::-1] for lis in text.split(" ")])
import re

def reverse_words(text):
    return re.sub(r'(\S+)', lambda x: x.group(1)[::-1], text)

assert reverse_words("Welcome to hogwarts!") == "emocleW ot !strawgoh"
assert reverse_words("hello         world") == "olleh         dlrow"
assert reverse_words("apple") == "elppa"
def reverse_words(text: str):
    for word in text.split():
        text = text.replace(word, word[::-1])
    return text
    public String reverse_words(String text) {
        String[] s = text.split(" ");
        String res = "";
        for (String s1 : s) {
            StringBuilder stringBuilder = new StringBuilder(s1);
            res =res + stringBuilder.reverse().toString()+" ";
        }
        return res;
    }
def reverse_words(text):
    return " ".join([''.join(reversed(list(x))) for x in text.split(" ") ])

assert reverse_words("Welcome to hogwarts!") == "emocleW ot !strawgoh"
assert reverse_words("hello   world") == "olleh   dlrow"
assert reverse_words("apple") == "elppa"
def reverse_words(text):
    return " ".join(lis[::-1] for lis in text.split(" "))

assert reverse_words("Welcome to hogwarts!") == "emocleW ot !strawgoh"
assert reverse_words("hello   world") == "olleh   dlrow"
assert reverse_words("apple") == "elppa"
def reverse_words(text):
    return ' '.join([w[::-1] for w in text.split(' ')])


assert reverse_words("Welcome to hogwarts!") == "emocleW ot !strawgoh"
assert reverse_words("hello   world") == "olleh   dlrow"
assert reverse_words("apple") == "elppa"
关闭