Regular expressions

Peter Otten __peter__ at web.de
Tue Nov 3 09:00:48 EST 2015


Tim Chase wrote:

> On 2015-11-03 10:25, Peter Otten wrote:
>> >>> How do I make a regular expression that returns true if the end
>> >>> of the line is an asterisk
>> >> 
>> >> Why use a regular expression?
>> >> 
>> >>   if line[-1] == '*':
>> >>     yep(line)
>> >>   else:
>> >>     nope(line)
>> 
>> Incidentally the code example has two "problems", too.
>> 
>> - What about the empty string?
> 
> Good catch: .endswith() works better.
> 
>> - What about lines with a trailing "\n", i. e. as they are usually
>> delivered when iterating over a file?
> 
> Then your string *doesn't* end with a "*", but rather with a
> newline. ;-)
> 
> Though according to the OP's specs, the following function would work
> too:
> 
>   def ends_in_asterisk(s):
>     return True
> 
> It *does* return True if the line ends in an asterisk (no requirement
> to make the function return False under any other conditions).

If a "line" is defined as a string that ends with a newline

def ends_in_asterisk(line):
    return False

would also satisfy the requirement. Lies, damned lies, and specs ;)




More information about the Python-list mailing list