Take the 2-minute tour ×
x = WAIT100MS
subroutines = ["WAIT"+str(range(1,256))+"MS"]
if x in subroutines:
    print "success"
    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?

share|improve this question
mgilson's answer will solve the immediate issue, but really, you should be using a regex here. –  Silas Ray Jan 3 '13 at 19:50
Think about the order things are happening. You generate the range, then turn it into a string, then try to do a join. Things are out of order. –  Mark Ransom Jan 3 '13 at 19:51
Do you actually need this list for any purpose other than checking if x in subroutines? If so, then Mark Ransom has explained the problem and mgilson the solution. If not, then (a) it's better as a set than a list, and (b) it's better to not generate it explicitly in the first place, presumably using some form of string processing, and NPE has provided a great solution. –  abarnert Jan 3 '13 at 19:59

3 Answers 3

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.

share|improve this answer
Ahh, so this is what OP wanted to do. I was having a hard time figuring out what OP was attempting ... –  mgilson Jan 3 '13 at 19:52

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):
        i = int(s[4:-2]))
    except ValueError:
        return False
    return s.startswith('WAIT') and s.endswith('MS') and (1 <= i < 256)
share|improve this answer

Why re when you can slice?

x = 'WAIT100MS'
n = int(x[4:-2])
if 1 < n < 256:
    print 'success'
    print 'invalid'
share|improve this answer
This fails to accept WAIT1MS, and can wrongly accept inputs that don't start with WAIT or end with MS. –  NPE Jan 3 '13 at 20:19
Actually it accepts 'WAIT1MS', tried with both 2.x and 3.x and it works. Your solution with re of course describes better the need but if you take for granted the syntax then slicing is the pragmatic way. –  Manuel Gutierrez Jan 4 '13 at 13:16
I hate to go on about this, but how can 1 < 1 < 256 evaluate to True, which is what you appear to be saying? –  NPE Jan 4 '13 at 13:17
Oh right, my bad, I thought you said the slicing part. just change the 1 for 0 and we're good to go. –  Manuel Gutierrez Jan 4 '13 at 14:42

Your Answer


