Python找出字符串开头有多少个0

题目介绍:给你一个字符串,字符串由数字组成,要求返回这个字符串的开头有多少个0

题目要求:

Input: A string, that consist of digits.

Output: An Int.

Example:beginning_zeros(‘100’) == 0

beginning_zeros(‘001’) == 2

beginning_zeros(‘100100’) == 0

beginning_zeros(‘001001’) == 2

beginning_zeros(‘012345679’) == 1

beginning_zeros(‘0000’) == 4

题目分析:先判断字符串是否为空,为空直接返回0,不为空则遍历字符串,定义一个count,遇到0counr就加1,如果不为0就结束循环,返回count

我的答案:

def beginning_zeros(number: str) -> int:
    # your code here
    count = 0
    if int(number[0]) != 0:
        return 0
    else:
        for i in number:
            if int(i) == 0:
                count += 1
            else:
                break
        return count


if __name__ == '__main__':
    print("Example:")
    print(beginning_zeros('100'))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert beginning_zeros('100') == 0
    assert beginning_zeros('001') == 2
    assert beginning_zeros('100100') == 0
    assert beginning_zeros('001001') == 2
    assert beginning_zeros('012345679') == 1
    assert beginning_zeros('0000') == 4
    print("Coding complete? Click 'Check' to earn cool rewards!")
Python教程

Python将列表中的字符串分割成多个【题目:Split Pairs】

2021-4-3 20:13:05

Python教程

python计数排序法是什么

2021-4-26 23:21:20

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
今日签到
有新私信 私信列表
搜索