反转句子中每个单词的 Python 程序?
我们这里使用了python中内置的函数。首先我们将句子分解成一个单词列表。然后反转每个单词并创建一个新列表,这里我们使用python列表推导技术并最后链接新单词列表并生成一个新句子。
范例
Input :: PYTHON PROGRAM Output :: NOHTYP MARGORP
算法
Step 1 : input a sentence. And store this in a variable s. Step 2 : Then splitting the sentence into a list of words. w=s.split(“”) Step 3 : Reversing each word and creating a new list of words nw. Step 4 : Joining the new list of words and make a new sentence ns.
示例代码
# Reverse each word of a Sentence # Function to Reverse words def reverseword(s): w = s.split(" ") # Splitting the Sentence into list of words. # reversing each word and creating a new list of words # apply List Comprehension Technique nw = [i[::-1] for i in w] # Join the new list of words to for a new Sentence ns = " ".join(nw) return ns # Driver's Code s = input("ENTER A SENTENCE PROPERLY ::") print(reverseword(s))
输出
ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM NOHTYP MARGORP
广告