-2

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?

erip
  • 16,374
  • 11
  • 66
  • 121
Greenev
  • 871
  • 6
  • 23
  • 2
    have you tried this? If you pass `''` then a child is empty but passing `None` has `None`; the other elements are present if you just want an empty child element see answer below – depperm Feb 09 '18 at 15:52
  • sorry, tried `''` only with if-else statement and got `''` – Greenev Feb 09 '18 at 16:15

3 Answers3

5

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.

erip
  • 16,374
  • 11
  • 66
  • 121
1

Couldn't you just use if statements?

def pass_empty_string(param):
    from lxml import etree
    if param is None or param == '':
        return etree.XML(f'<child></child>')
    xml = etree.XML(f'''
    <root>
        <child>text</child>
        <child>{param}</child>
        ...
    </root>''')
    return xml
erip
  • 16,374
  • 11
  • 66
  • 121
SuperStew
  • 2,857
  • 2
  • 15
  • 27
1

A simple if statement will do:

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

xml looks like this:

<root>
    <child>text</child>
    <child></child>
</root>
erip
  • 16,374
  • 11
  • 66
  • 121
Farhan.K
  • 3,425
  • 2
  • 15
  • 26