且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何颠倒字符串中单词的顺序

更新时间:2023-02-01 18:59:34

您可以使用 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'