如何反转字符串中单词的顺序

How to reverse the order of the words in a string

例如:

 input:  I live in New York
 output: York New in live I

P.S:我用过s[::-1],这只是把字符串倒转,比如 kroY weN ni evil I,但这不是所需的输出。 我也试过了:

def rev(x) :
    x = x[::-1]
    for i in range(len(x)) :
        if x[i] == " " :
            x = x[::-1]
            continue
        print x

但这也不对。 请帮助我编写代码。

您可以使用 split to get the separate words, reverse to reverse the list, and finally join 再次加入它们以组成最终字符串:

s = "This is New York"
# split first
a = s.split()
# reverse list
a.reverse()
# now join them
result = " ".join(a)
# print it
print(result)

结果:

'York New is This'
my_string = "I live in New York"
reversed_string = " ".join(my_string.split(" ")[::-1])

这是一个 3 阶段过程 - 首先我们将字符串拆分为单词,然后我们将单词反转,然后再次将它们连接在一起。

第一种方法

您需要拆分给定的字符串,以便您在字符串中给出的任何单词都将保存为列表数据类型。然后你可以反转列表元素并用 spaces.

加入它
x = input("Enter any sentence:")
y = x.split(' ')
r = y[::-1]
z = ' '.join(r)

print(z)

第二种方法

与第一个相同,但在反转之后,您需要遍历列表并通过在每个列表元素后插入空 space(“”)来打印元素。

x = input("Enter any sentence: ")
y = x.split(' ')
r = y[::-1]

for i in r:
    print(i , end=" ")

例子

  • 输入:我住在纽约
  • 输出:York New in live I

这可以是另一种方法,但这个有效:

a="this is new york"
b=a.split(" ")
tem=[]
i=-1
for j in range(len(b)):
   tem.append(b[i])
   i-=1
print(*tem)