x = WAIT100MS
subroutines = ["WAIT"+str(range(1,256))+"MS"]
if x in subroutines:
print "success"
else:
print "invalid"
I'm trying to create a piece of code where if WAITXMS is between 1 and 255, it will be accepted, otherwise it will not.
the range() function just generates a list, so I thought I would be able to use
" ".join("WAIT"+str(range(1,256))+"MS"),
to end up with a string like x.
However using the join() function with range() doesn't seem to work like I'd expect, and instead gives me a list as normal like "WAIT[1,2,3,4,...]MS". What should I do?
I think you want something like:
''.join("WAIT%dMS"%i for i in range(1,256))
Here's a better way I think:
def accept_string(s):
try:
i = int(s[4:-2])
except ValueError:
return False
return s.startswith('WAIT') and s.endswith('MS') and (1 <= i < 256)
I would do something like:
x = "WAIT100MS"
m = re.match(r"WAIT(\d+)MS$", x)
accept = m is not None and 1 <= int(m.group(1)) <= 255
I think that iterating over all acceptable numbers (let alone building and storing all WAIT<n>MS strings) is unnecessarily wasteful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With