Check if the string is binary number in Python

Method 1

def method_1(s:str):
    for i in s:
        if i not in ['0','1']:
            return False
    return True

Method 2

def method_2(s):
    return bool(re.match('[01]+', s))

Method 3

def method_3(s):
    try:
        int(s, 2)
        return True
    except ValueError:
        return False

Execution time test - using timeit

import re
import timeit


def method_1(s: str):
    for i in s:
        if i not in ['0', '1']:
            return False
    return True


def method_2(s):
    return bool(re.match('[01]+', s))


def method_3(s):
    try:
        int(s, 2)
        return True
    except ValueError:
        return False


def main():
    time = timeit.repeat(lambda: method_1("101010111111"))
    print("Method 1 time - ", time)
    time = timeit.repeat(lambda: method_2("101010111111"))
    print("Method 2 time - ", time)
    time = timeit.repeat(lambda: method_3("101010111111"))
    print("Method 3 time - ", time)


if __name__ == "__main__":
    main()

Output

Method 1 time -  [0.6567885, 0.7155738999999999, 0.7135714999999998, 0.6630374999999997, 0.8226202000000002]
Method 2 time -  [1.2000119000000002, 1.2037982999999999, 1.2008302999999998, 1.3448011999999991, 1.1958587999999999]
Method 3 time -  [0.3451967000000007, 0.3352440999999988, 0.37957380000000107, 0.3730146000000012, 0.40214969999999894]

you can see that method 3 (int(s, 2)) is the the fastest.