Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: using range() with " ".join()

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?

like image 748
evilllamas Avatar asked Dec 04 '25 17:12

evilllamas


2 Answers

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)
like image 104
mgilson Avatar answered Dec 06 '25 08:12

mgilson


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.

like image 32
NPE Avatar answered Dec 06 '25 07:12

NPE