[Python-ideas] New explicit methods to trim strings

MRAB python at mrabarnett.plus.com
Wed Apr 3 13:54:21 EDT 2019


On 2019-04-03 03:06, Stephan Hoyer wrote:
> On Tue, Apr 2, 2019 at 5:43 PM Eric V. Smith <eric at trueblade.com 
> <mailto:eric at trueblade.com>> wrote:
> 
>     PS: I really tried to find a way to use := in this example so I could
>     put the assignment inside the 'if' statement, but as I think Tim Peters
>     pointed out, without C's comma operator, you can't.
> 
> 
> Conceivably cut_prefix could return None if not found. Then you could 
> write something like:
> 
> if (stripped := cut_prefix(line, "INFO>")) is not None:
>       print(f"control line {stripped!r}")
> else:
>       print(f"data line {line!r}")
> 
> You could even drop "is not None" in many circumstances, if you know the 
> cut string will be non-empty. That's actually pretty readable:
> 
> if stripped := cut_prefix(line, "INFO>"):
>       print(f"control line {stripped!r}")
> else:
>       print(f"data line {line!r}")
> 
-1

Sometimes you just want to remove it if present, otherwise leave the 
string as-is.

I wouldn't want to have to write:

     line = line.lcut("INFO>") or line



More information about the Python-ideas mailing list