如何以相同的句子顺序反转字符串中的每个单词? [英] How do I reverse each word in a string, but in the same sentence order?

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

问题描述

我尝试这样做

while 1:
    line = input('Line: ')
    print(line[::-1])

,但所做的只是颠倒了整个句子,我想知道是否有人可以通过一个将 hello world转换为 olleh dlrow而不是 dlrow olleh的程序来帮助我,我如何制作一个循环,当输入什么都不是或者只是一个空格时就停止了?

but all that did was reverse the whole sentence, I was wondering if someone could help me with a program that converts 'hello world' to 'olleh dlrow' instead of 'dlrow olleh', and how do I make a loop that stops when the input is nothing, or just a space? Thank you in advanced!

推荐答案

您需要拆分句子,反转单词,然后重新组合。

You need to split the sentence, reverse the words, then reassemble.

最简单的拆分方法是在空白处使用 str.split()进行拆分。那么,重组只是将反向单词重新加上空格的情况:

The simplest way to split is to do so on whitespace, with str.split(); reassembly is then just a case of re-joining the reversed words with a space:

' '.join([word[::-1] for word in line.split()])

Demo:

>>> line = 'hello world'
>>> ' '.join([word[::-1] for word in line.split()])
'olleh dlrow'

这篇关于如何以相同的句子顺序反转字符串中的每个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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