My objective is to have conditional formatting in a string where the condition is inside the string.
This can be done with f-strings like so:
>>> my_name = 'Steve'
>>> f"hello, {my_name if my_name else 'world'}"
'hello, Steve'
>>> my_name = ''
>>> f"hello, {my_name if my_name else 'world'}"
'hello, world'
But, as f-strings are just syntax and not objects, they are not useful for my use-case.
I could instead use the format method like so (as suggested in How to implement conditional string formatting?):
>>> my_name = 'Steve'
>>> s = 'hello, {name}'
>>> s.format(name=my_name if my_name else 'world')
'hello, Steve'
>>> my_name = ''
>>> s.format(name=my_name if my_name else 'world')
'hello, world'
But then the condition wouldn't be part of the string.
So I'm trying to achieve something that behaves like so:
>>> s = "hello, {name if name else 'world'}"
>>> s.format(name='Steve')
'hello, Steve'
>>> s.format(name='')
'hello, world'
But this fails with the following message: KeyError: "name if name else 'world'"
Any way to do this other then implementing it myself?