python - 用 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)
我一遍又一遍地敲着头。
解决方案
这是一个潜在的实现:
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
推荐阅读
- javascript - v-for key 作为 VueJS 中的 v-model 不起作用
- android - 可以像 imageView 一样为 layer-list 中的项目设置 scaleType 吗?
- html - 具有固定标题的 HTML Bootstrap 表
- selenium - Selenium 自动化脚本标签用作选择标签(下拉),其中带有复选框以进行多项选择?
- android - 带有反应导航的firebase动态链接
- java - 如何在 Editor-IntelliJ 插件-Swing 上进行自动完成文本建议
- ios - Tensorflow Lite .tflite 模型不适用于 iOS,但适用于 android
- angular - Angular 5:如何从表中动态添加和删除行中获取值
- matlab - 使用滑动内核(Matlab)在 2D 网格上平均 3D 点云的属性
- javascript - 如何使用 PHP 在邮件中添加超链接