Recognize a string containing only digits and "/" symbols in Python

I have a short string, and need a way to recognize whether there are only digits and/or "/" symbols in that string. If there are alphabetical or some other symbols in the string – it is a no go. Only digits and "/" are allowed.

For example:

a = ‘123456’ – green light

b = ‘123//6’ – green light

c = ‘1m3456’ – a no go

d = ‘1/80o0’ – a no go

>Solution :

Just use set arithmetics

def onlyallowed(text,allowed="/0123456789"):
    return set(text).issubset(allowed)
print(onlyallowed("123456")) # True
print(onlyallowed("123//6")) # True
print(onlyallowed("1m3456")) # False
print(onlyallowed("1/80o0")) # False

Explanation: convert text to set (of characters) and check if all these character are present in allowed. Optional allowed might be used to deploy another set of allowed character, for example to allow only 0s and 1s:

print(onlyallowed("01011",allowed="01"))  # True

Leave a Reply