首页 > 解决方案 > 用 Python 处理文档

问题描述

虚构模块的文档:

weird.reverse(text, [start, [end]])

返回在开始到结束范围内反转的文本副本。

如果指定了可选参数 start 和 end,则此函数反转切片text[start:end],但保持切片外部的文本不变。例如:

>>> weird.reverse('abCDEfg',2,5)
'abEDCfg'

如果未指定 start 或 end,则反向切片分别从字符串的开头开始或在字符串的结尾结束。例如:

>>> weird.reverse('abCDEfg',2)
'abgfEDC'

参数:
text (str) – 要(部分)反转的文本 start (int) – 要反转的切片的开头 end (int) – 要反转的切片的结尾 返回:
在 start to 范围内反转的文本副本结尾。

返回类型:
str

问题:这些表达式返回什么?

weird.reverse('abcef',-3)
weird.reverse('abcef',end=2)    

我一遍又一遍地敲着头。

标签: python

解决方案


这是一个潜在的实现:

def reverse(text, start=None, end=None):
    if start is None and end is None:
        return text[::-1]
    if end is None:
        return text[:start] + text[start:][::-1]
    if start is None:
        return text[:end][::-1] + text[end:]
    return text[:start] + text[start:end][::-1] + text[end:]

使用此代码,运行

print(reverse('abcef',-3))
print(reverse('abcef',end=2))

给出:

abfec
bacef

切片文档链接:https ://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html


推荐阅读