How can I get the first two digits of a number?

前端 未结 4 1526
-上瘾入骨i
-上瘾入骨i 2020-12-30 19:31

I want to check the first two digits of a number in Python. Something like this:

for i in range(1000):

    if(first two digits of i == 15):
        print(\"         


        
4条回答
  •  青春惊慌失措
    2020-12-30 20:36

    You can use a regular expression to test for a match and capture the first two digits:

    import re
    
    for i in range(1000):
        match = re.match(r'(1[56])', str(i))
    
        if match:
            print(i, 'begins with', match.group(1))
    

    The regular expression (1[56]) matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.

    Output:

    15 begins with 15
    16 begins with 16
    150 begins with 15
    151 begins with 15
    152 begins with 15
    153 begins with 15
    154 begins with 15
    155 begins with 15
    156 begins with 15
    157 begins with 15
    158 begins with 15
    159 begins with 15
    160 begins with 16
    161 begins with 16
    162 begins with 16
    163 begins with 16
    164 begins with 16
    165 begins with 16
    166 begins with 16
    167 begins with 16
    168 begins with 16
    169 begins with 16
    

提交回复
热议问题