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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿