1.计算数字最后有几个零
(1)字符串函数rstrip():删除字符串末尾指定字符
def end_zeros(num:int) -> int:
return len(s:=str(num))-len(s.rstrip('0'))
(2)re.search():使用正则表达式
def end_zeros(num:int) -> int:
import re
return len(re.search('0*$', str(num)).group())
2. 字符串转置
(1)字符串的切片:[开始索引:结束索引:步长]
def end_zeros(val:str) -> str:
return val[::-1]
(2)列表函数insert():指定位置插入
def end_zeros(val:str) -> str:
new = []
for i in val:
new.insert(0,i)
return ''.join(new)
3.列表截取
For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove all elements that go before 3 - which is 1 and 2.
We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn’t be changed. (2) if the list is empty, then it should remain empty.
Input: List and the border element.
Output: Iterable (tuple, list, iterator …).
def remove_all_before(items, border):
try:
return items[items.index(border):]
except ValueError:
return items