python - 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")
解决方案
我们可以在这里使用元组解包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]: ''
推荐阅读
- google-apps-script - 将用户配置 URL 的 Google 表格插件的动态 URL 列入白名单
- json - JSONAARAY 对象动态键时解析
- linux - Linux上的SQLCMD或SQLPACKAGE?
- python - OpenCv imdecode 为 HEIC 文件返回无
- javascript - 将全局值绑定到角度的 ValidationErrors
- flutter - Flutter 发送多条消息,分享插件
- c# - 无法加载文件或程序集 System.Collections,版本 = 4.0.11.0
- javascript - 找不到名称“Highcharts”.ts(2304)
- html - 想要创建具有相似参数的自定义 numericRangeInput
- java - 获取 I/O 异常