首页 > 解决方案 > 在 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])

标签: pythonstring

解决方案


代码

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'

推荐阅读