如何在python中将字符串右移并反转它?

2024-10-01 17:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

将单词向右移动,然后反转。在

您应该将单词右移并反转,然后返回如下:

>>> shift_reverse('Introduction to Computer Programming')
gnimmargorP noitcudortnI ot retupmoC

我试图用这个方法来找到上面的答案,但似乎行不通 请帮忙:(

^{pr2}$

但我得到的指纹是

[evaluate untitled-3.py]
eM I uoY

Tags: to方法答案shiftot单词computerprogramming
3条回答

new_str = new_str[::1]中,您将反转整个字符串,每个字符对应一个字符。在

ghi abc def
fed cba ihg

你必须把list中的每个单词颠倒过来。在

^{pr2}$

以下是功能的逐步说明:

创建shift函数将最后一个单词移到开头:

def shift(sentence):
    words = sentence.split()
    return ' '.join([words[-1]] + words[:-1])

创建reverse函数来反转句子中的所有单词(使用list comprehension):

^{pr2}$

创建shift_reverse以反转所有单词,然后shift最后一个放在开头:

def shift_reverse(sentence):
    return shift(reverse(sentence))

结果:

shift_reverse('Introduction to Computer Programming')

输出:

'gnimmargorP noitcudortnI ot retupmoC'

您需要反转每个重新排序的列表:

reordered = l[-1:] + l[:-1]
new_str = ' '.join(word[::-1] for word in reordered)

相关问题 更多 >

    热门问题