builtin regular expressions?
Mirco Wahab
wahab at chemie.uni-halle.de
Sat Sep 30 10:52:27 EDT 2006
Thus spoke Jorge Godoy (on 2006-09-30 14:37):
> Antoine De Groote <antoine at vo.lu> writes:
>> I'm sure there are good reasons, but I just don't see them.
>> Python Culture says: 'Explicit is better than implicit'. May it be related to
>> this?
>
> See if this isn't better to read:
>
> def print_message(some_str):
> if some_str.startswith('track='):
> print "Your track is", some_str[6:]
> elif some_str.startswith('title='):
> print "It's a title of", some_str[6:]
> elif some_str.startswith('artist='):
> print "It was played by", some_str[7:]
> else:
> print "Oops, I dunno the pattern for this line..."
> return
>
> for line in ['track="My favorite track"', 'title="My favorite song"',
> 'artist="Those Dudes"', 'Something else']:
> print_message(line)
I don't see the point here, this example can be
translated amost 1:1 to Perl and gets much more
readable in the end, consider:
sub print_message {
if (/^(track=)/ ){ print 'Your track is ' .substr($_, length $1)."\n" }
elsif(/^(title=)/ ){ print 'It\'s a title of '.substr($_, length $1)."\n" }
elsif(/^(artist=)/){ print 'It was played by '.substr($_, length $1)."\n" }
else { print "Oops, I dunno the pattern for this line...\n" }
}
print_message for ( 'track="My favorite track"', 'title="My favorite song"',
'artist="Those Dudes"', 'Something else' );
Now one could argue if simple Regexes like
/^track=/ are much worse compared to
more explicit formulations, like
str.startswith('track=')
> I came from Perl and was used to think with regular expressions for
> everything. Now I rarely use them. They aren't needed to solve
> most of the problems.
OK, I do Perl and Python side by side and didn't reach
that point so far, maybe beause I read the Friedel-Book
( http://www.oreilly.com/catalog/regex2/reviews.html )
sometimes and actually *like* the concept of regular expressions.
Regards
Mirco
More information about the Python-list
mailing list