python - 给定一个句子,返回一个单词颠倒的句子

标签 python arrays string list reverse

def master_yoda(text):
    txt_elements=text.split()
    index=-1
    reverse=[]
    i=0
    while i <= len(txt_elements):
        reverse.append(txt_elements[index])
        index=index-1
        i+=1
    final=' '.join(reverse)
    return final
print(master_yoda('i adore that'))

我不明白为什么我总是收到关于取消缩进的错误。

这是一个例子:

  • 输入:“我很漂亮”
  • 输出:“美丽的我”

最佳答案

改变

while i <= len(txt_elements):

while i < len(txt_elements):

请记住,您可以改为这样做:

def master_yoda(text):
    return ' '.join(text.split()[::-1])

在此示例中,[::-1] 使用切片反转列表。您也可以使用 reversed() python 内置 - 请参阅 comment by @wjandrea

关于python - 给定一个句子,返回一个单词颠倒的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59196910/

相关文章:

c++ - 使用带有字符串定界符的 boost::tokenizer

python - 体面的数字 |帮助降低时间复杂度

javascript - 将 JavaScript JSON 数据转换为 Python JSON

ios - 从数组中删除项目(带有来自 API 的 JSON 的 Restkit 项目)

python - 在 Python 中找到最匹配的 block /补丁

c++ - 没有匹配函数调用 'begin(int [n])'

C:删除文件中所有出现的单词

python - 无法抓取页面的同一部分,唯一的区别是 div 和 span

python - 在 python 中配置根记录器

string - 在 Go 中解析格式化字符串