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.
Why re when you can slice?
x = 'WAIT100MS'
n = int(x[4:-2])
if 1 < n < 256:
print 'success'
else:
print 'invalid'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.