python - 在 Python 中查找所需的数字
问题描述
一个号码在那里。如果数字尾随零,则应将尾随零之前的三位数字附加到输出字符串中。如果不以零结尾,则将最后三位数字附加到输出字符串。如果前面有零,则将其忽略。
Sample input:362880 Sample OutPut:288
Sample input:892002300 Sample OutPut:23
Sample input:460 Sample OutPut:46
Sample input:1089 Sample OutPut:89
Sample input:5 Sample OutPut:5
我是 python 新手,已经编写了以下代码,但无法获得所需的输出,请帮助我。
a='3620880'
b=''
for i in a[::-1]:
if int(i)!=0 and len(b)<3:
b=b+i
print(b[::-1])
解决方案
代码
a.rstrip("0")[-3:].lstrip("0")
在s 上使用lstrip()
和。后面的最后 3 个字符可以通过 选择。rstrip()
'0'
rstrip()
str[-3:]
例子
'362880'.rstrip("0")[-3:].lstrip("0")
# '288'
'5'.rstrip("0")[-3:].lstrip("0")
# '5'
'1089'.rstrip("0")[-3:].lstrip("0")
# '89'
推荐阅读
- c# - 在 C# 中使用 Selenium 进行测试 - 我需要测试更改 XPath 的网站
- rust - 具有多个生命周期参数的结构的真实示例是什么?
- c - 英特尔 safestringlib 中的未定义行为
- drools - 我想根据流口水的某些条件总结两个不同的属性
- php - TCPDF 不创建 pdf 当数据量很大时
- android - 如何使用 RxJava2 从数据库中获取最新数据并显示在顶部
- kendo-grid - Kendo MVC - 子网格 - 客户端模板 - 加载 - 异常/未定义
- matlab - 将操作应用于每个单元格都是一个多边形的单元格数组
- message - 如何抑制vertica中的输出消息
- reactjs - IIS 服务器上的 React 部署