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
CodePudding user response:
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 0
s and 1
s:
print(onlyallowed("01011",allowed="01")) # True
CodePudding user response:
import re
def recognize(self):
if re.search(r"[a-b]", self) is not None:
print("Red Light")
elif re.search(r"[0-9]|/", self) is not None:
print("Green Light")
recognize(your_string)
If the recognize()
function finds a letter in the string, the output will be a "Red Light", otherwise if it finds a number or a '/', the output will be a "Green Light".
CodePudding user response:
I believe this is what you're looking for:
strings = ['123456', '123//6', '1m3456', '1/80o0']
print([string.replace('/', '').isdigit() for string in strings])
Simply removing any / characters if exist and checking if it is all digits seems more readable to me, and also more in tune with the way you described it in english :)
Hope this helped. Cheers!