Search code examples
pythonlxmlstring-literalsf-string

How can I pass an empty string into triple quoted f-string in Python?


Here is a function using a triple quoted f-string with lots of sub-elements:

def pass_empty_string(param):
    from lxml import etree
    xml = etree.XML(f'''
    <root>
        <child>text</child>
        <child>{param}</child>
        ...
    </root>''')
    return xml

Is it possible to get an empty </child> element when param is getting None or '' value?


Solution

  • You can accomplish this with or:

    f"<child>{param or ''}</child>"
    

    Anything in the braces is evaluated as an expression, so...

    >>> param = None
    >>> f"<child>{param or ''}</child>"
    '<child></child>'
    >>> param = ''
    >>> f"<child>{param or ''}</child>"
    '<child></child>'
    >>> param = "some valid child"
    >>> f"<child>{param or ''}</child>"
    '<child>some valid child</child>'
    

    Both '' and None are falsy values, so it will fall back to the RHS of the or, which will be just an empty string.