Home > Software engineering >  How do I check if a string starts with two numbers in Python?
How do I check if a string starts with two numbers in Python?

Time:07-02

I want to take in a str via usr_input = input("Input here: ") and then check if that string starts with two digits.

Thanks in advance for any help.

CodePudding user response:

try this:

usr_input = input("Input here: ")
if(len(usr_input) >= 2 and usr_input[:2].isdigit()):
    print('yes') # write your code here

CodePudding user response:

For the sake of variety:

import re
string=input()
bool(re.search(r'^\d{2}',string))

CodePudding user response:

luckily, there's a method for this.

a solution is

def begins_with_two_digits(your_str):
    first=your_str[0]
    second=your_str[1]
    if first.isdigit() and second.isdigit():
        return True
    else:
        return False

the .isdigit() method will check if the first and second characters are digits. in practice, though, you want something like this:

if your_str[0:2].isdigit():
    #stuff
else:
    #some other stuff
  • Related