例如:
input: I live in New York
output: York New in live I
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
但这也是不正确的请帮助我编写代码.
您可以使用split获取单独的单词,reverse反转列表,最后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)
Run Code Online (Sandbox Code Playgroud)
结果是:
'York New is This'
Run Code Online (Sandbox Code Playgroud)
my_string = "I live in New York"
reversed_string = " ".join(my_string.split(" ")[::-1])
Run Code Online (Sandbox Code Playgroud)
这是一个3阶段的过程 - 首先我们将字符串拆分为单词,然后我们反转单词然后再将它们连接在一起.
| 归档时间: |
|
| 查看次数: |
16509 次 |
| 最近记录: |