On Thu, Sep 17, 2020 at 2:38 PM Dennis Sweeney <sweeney.dennis...@gmail.com>
wrote:

> === Existing way of achieving this ===
>
> As of now, you could achieve the behavior with regular expressions:
>
>     >>> import re
>     >>> pattern = re.compile(r'It is (.+):(.+) (.+)')
>     >>> match = pattern.fullmatch("It is 11:45 PM")
>     >>> hh, mm, am_or_pm = match.groups()
>     >>> hh
>     '11'
>
> But this suffers from the same paint-by-numbers, extra-indirection
> issue that old-style string formatting runs into, an issue that
> f-strings improve upon.
>

This seems a bit of an unfair basis for comparison. I would probably write
it on one line:

    hh, mm, am_or_pm = re.fullmatch(r'It is (.+):(.+) (.+)', "It is 11:45
PM").groups()

Which is not great but not that bad either.

More importantly, I would probably validate the input properly in my regex:

    It is (\d+):(\d+) (AM|PM)

I would much rather be able to use regex syntax like that for proper
matching and validation than format specifiers like .02f which AFAIK
already falls down in the given example with AM|PM. So maybe something like:

    f"It is {hh:\d+}:{mm:\d+} {am_or_pm:AM|PM}" =  "It is 11:45 PM"

And then a syntax to also convert to an int would be nice, e.g.
`{hh:\d+:int}`, although it probably needs a lot more thought than that.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GJ5477CHTCPME7UV64GF7AJ63VXNLT44/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to