Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading