Perl is worse!
Eric Lorenzo
zo at angband.org
Sat Jul 29 13:54:16 EDT 2000
Steffen Ries <steffen.ries at sympatico.ca> writes:
> grey at despair.rpglink.com (Steve Lamb) writes:
> > On Fri, 28 Jul 2000 19:29:52 -0400, Karl Ulbrich <kulbrich at yahoo.com> wrote:
> > >If they already contained numbers (well, strings of digits), and
> > >you were certain, then simply:
> >
> > > a = int(b)
> >
> > As stated, that would work except Python returns a None on a
> > no-match and None can't be converted.
>
> use:
> a = int(b or 0)
> then.
Steve's entire die-parsing problem could be cleaned up with the tip
above, and a better regexp. I can't see any good reason for him to
put the modifier's sign into a seperate group from the digits, and I
can't see any reason to use two big regexps then the two forms of
expression (with or without modifier) vary by only a bit at the end.
How about this:
import re
parse_die_re = re.compile('^(\d{1,2})[dD](\d{1,3})([+-]\d{1,3}|)$')
def parse_die(s):
try:
g = parse_die_re.match(s).groups()
except AttributeError:
raise ValueError('Not a valid die expression')
return int(g[0]), int(g[1]), int(g[2] or 0)
This the always generates 3 groups, the last one being an explicitly
signed integer when there's a modifier present, and the empty string
otherwise. Since the empty string behaves as a boolean false, the
'g[2] or 0' thing works.
The interesting thing about this is that it's actually an example of
Python behaving the way that Steve says it doesn't (but should): g[2],
a string, is treated like a boolean when used with the boolean
operator 'or', but goes back to being a string once the result of that
expression gets passed into int. If Python was *really* as completely
anal-retentive about types as he thinks, there would be a BooleanType,
and the 'or' operator would choke on both the string and the integer.
Eric
More information about the Python-list
mailing list