tags:

views:

73

answers:

1

I've got some Perl code like this:

my $match = $matches{$key}
            ? "$matches{$key} was a match!"
            : "There was no match."

How is this best rewritten in Python? I'm trying to avoid getting a KeyError.

+3  A: 

This.

message = "%s was a match"%(matches[key],) if key in matches else "There was no match."
S.Lott
Why is the , necessary in matches[key], ?
mike
Can I just say this? message = "%s was a match" % matches[key] if key in matches else "There was no match"
mike
The comma is not necessary. However, it's good style to always use a tuple as the right argument to % string formatting.
Benjamin Peterson
@Benjamin Peterson: just out of curiosity, why?
Brian R. Bondy
format % tuple is the standard form; (x,) is a singleton tuple. (x,y) is a two-tuple ("double"), (z,y,x) is a three-tuple ("triple"). Python can tolerate format % value IF (and only if) the value is not itself a sequence. Strings are sequences. So format % (string,) is usually required.
S.Lott
@S.Lott: Thanks for the explanation. +1
Brian R. Bondy
I don't get it. If i do: x = 'foo' ; "%s" % x ...it seems to return 'foo', which is expected. Doesn't this violate S.Lott's most recent comment?
mike
@Mike: My mistake -- the ambiguity only arises when trying for format a tuple. http://docs.python.org/library/stdtypes.html#id5 Then you need to enclose the tuple to a singleton of it: x=(1,2); "%s"%(x,) is required.
S.Lott