如何颠倒字符串中单词的顺序 [英] How to reverse the order of the words in a string

查看:53
本文介绍了如何颠倒字符串中单词的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

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

P.S: I have used s[::-1], this just reverses the string, like kroY weN ni evil I, but this is not the desired output. I also tried :

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

但这也是不正确的.请帮我写代码.

But this also stands incorrect. Kindly help me in writing the code.

推荐答案

您可以使用 split 得到单独的词,reverse 反转列表,最后 join 再次连接它们以形成最终字符串:

You can use split to get the separate words, reverse to reverse the list, and finally join to join them again to make the final string:

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'

这篇关于如何颠倒字符串中单词的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆