[英]How to reverse the order of the words in a string
例如:
input: I live in New York
output: York New in live I
PS:我使用了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
但这也是不正确的。 请帮助我编写代码。
my_string = "I live in New York"
reversed_string = " ".join(my_string.split(" ")[::-1])
这是一个 3 个阶段的过程 - 首先我们将字符串拆分为单词,然后我们反转单词,然后再次将它们连接在一起。
您需要拆分给定的字符串,以便您在字符串中给出的任何单词都将保存为列表数据类型。 然后你可以反转列表元素并用空格连接它。
x = input("Enter any sentence:")
y = x.split(' ')
r = y[::-1]
z = ' '.join(r)
print(z)
与第一个相同,但在反转之后,您需要通过在每个列表元素后插入空格 (" ") 来遍历列表并打印元素。
x = input("Enter any sentence: ")
y = x.split(' ')
r = y[::-1]
for i in r:
print(i , end=" ")
这可以是另一种方法,但这是有效的:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.