2015-04-30 13 views
5

将单词右移,然后将其倒转。如何将字符串右移并在python中将其逆转?

你应该采取一个字右移和扭转它然后返回如下:

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

我试着用这种方法找到了上面的回答,但它似乎没有工作 请帮助:(

s= "I Me You" 
def shift_reverse(s): 
    l= s.split() 
    new_str= ' '.join(l[-1:] + l[:-1]) 
    new_str = new_str[::-1] 
    return (new_str) 

print (shift_reverse(s)) 

但打印我得到的是

[evaluate untitled-3.py] 
eM I uoY 
+0

无论是反分裂重新排序联接,或分重新排序,反向连接。你既没有做。 –

回答

1

您将n EED扭转每个重新排序列表:

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

这应该为你工作

s= "Introduction to Computer Programming" 
def shift_reverse(s): 
    l= s.split() 
    l = [l.pop()]+ l 
    return ' '.join(i[::-1] for i in l) 

print (shift_reverse(s)) 

输出:

gnimmargorP noitcudortnI ot retupmoC 
+0

为什么downvote?它具有OP所要求的输出 – letsc

0

这里是一步步与功能:

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

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

创建reverse功能扭转所有单词在句子中(使用list comprehension):

def reverse(sentence): 
    return ' '.join([word[::-1] for word in sentence.split()]) 

创建shift_reverse扭转所有单词,然后shift到开始最后:

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

结果:

shift_reverse('Introduction to Computer Programming') 

输出:

'gnimmargorP noitcudortnI ot retupmoC' 
0

new_str = new_str[::1],你倒车每个字符整个字符串,字符。

ghi abc def 
fed cba ihg 

您必须反转单词list中的每个单词。

def shift_reverse(string): 
    words = string.split() 
    shifted_words = [words[-1]] + words[:-1] 
    return ' '.join([word[::-1] for word in shifted_words]) 
0

你可以加入,在旋转的分裂名单产生相反的词生成器表达式:

>>> s = 'Introduction to Computer Programming' 
>>> ' '.join(w[::-1] for w in (lambda l: l[-1:] + l[:-1])(s.split())) 
'gnimmargorP noitcudortnI ot retupmoC' 
0
def shift_reverse(s): 
    rev = ["".join(reversed(word)) for word in s.split(" ")] 
    return "{} {}".format(rev.pop(), " ".join(rev)) 

扭转所有的琴弦,弹出最后关闭的逆转单词列表,并加入余。

+1

虽然代码是赞赏的,但它应该总是有一个附随的解释。这不需要很长时间,但它是预期的。 – peterh

0

您可以将字符串在转变,反向每个项目:

>>> phrase = 'Introduction to Computer Programming' 
>>> new = ' '.join([word[::-1] for word in [phrase.split()[-1]]+phrase.split()[:-1]]) 
>>> print new 
gnimmargorP noitcudortnI ot retupmoC 
>>> 
相关问题