Search code examples
pythonpython-3.xformattingstring-formattingpython-3.8

formatting with optional "replacement fields" in python


there is such a code:

text = "{first}, {second}, {etc}"

print(text.format(first="1", etc="34.."))

when it is executed, I (expectedly) get a KeyError.
my question is this:
Is it possible to make formatting not affect second, but just leave "{second}"?
that is, in my case, I want to get: 1, {second}, 34..

Suppose I don’t know in advance which field I will format, what then?


Solution

  • I decided to create a library to solve this problem: pyformatting.
    Here is the solution to problem with pyformatting:

    >>> from pyformatting import optional_format
    >>> text = "{first}, {second}, {etc}"
    >>> optional_format(text, first="1", etc="34..")
    '1, {second}, 34..'
    

    The only problem is pyformatting doesn't support python 2. pyformatting supports python 3.1+ If i see any feedback on the need for 2.7 support i think i will add that support.