首页 > 解决方案 > Rearranging letters but keep the first and last the same

问题描述

I have to rearrange a five letter word. The code I have right now works in the sense that it rearranges the word but I need it to keep the first and last letters the same. I've tried adding different parts and splitting.

How should I change it to keep these parts the same?

def in_lat(word):
    return word[::-1] 

assert (in_lat("first") == "fsrit")

标签: python

解决方案


我们可以在这里使用元组解包1。我们只是将单词作为第一个字符、字符串的中间部分和最后一个字符分开。我们可以推广这种方法来处理任意长度的字符串。

def func(wrd):  # if we give "abcd" as `wrd`
    if len(wrd) < 2:
        return wrd
    else:
#       'a' ['b', 'c'] 'd'  
#        ‖      ‖      ‖
        first, *mid, last = wrd
        return "".join([first, *mid[::-1], last])
      # return first + "".join(mid[::-1]) + last 

示例输出:

In [16]: func("a")                                                              
Out[16]: 'a'

In [17]: func("ab")                                                             
Out[17]: 'ab'

In [18]: func("abc")                                                            
Out[18]: 'abc'

In [19]: func("abcd")                                                           
Out[19]: 'acbd'

In [20]: func("")                                                               
Out[20]: ''

1. PEP 3132 -- 扩展的可迭代拆包


推荐阅读