0

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?

CarlosHSF
  • 51
  • 4
  • 2
    Why do you think you need to do it this way? What can this hypothetical approach solve that f-strings and regular string formatting can't? You mentioned that f-strings don't work for your use-case. What is your use-case, exactly? Is this your attempted solution to a larger problem, or are you just curious to see if it can be done? – Paul M. Apr 21 '22 at 19:54
  • 1
    just to mention that `{my_name if my_name else 'world'}` from the `f-string` is better as `{my_name or 'world'}` – buran Apr 21 '22 at 19:59
  • s = lambda my_name = None: f"hello, {my_name if my_name else 'world'}" print(s('Carlos')) – lmielke Apr 21 '22 at 20:06
  • @PaulM. This is for a college project. I don't necessarily need to do it this way, but it seemed like a simple approach. Currently I'm receiving a string of which I know nothing, I just know that I have some variables that might be arguments of keys in that string. So I would format the string providing those arguments and the string would know what to do with them. This works just fine for replacement, but not for conditional replacement. – CarlosHSF Apr 21 '22 at 21:43

1 Answers1

0

If you want the condition to be a part of string, use a templating engine like Jinja2:

# pip install jinja2
from jinja2 import Template

s = Template("hello, {{ name|default('world') }}"

Output:

>>> s.render(name='Steeve')
'hello, Steeve'

>>> s.render()
'hello, world'
Corralien
  • 70,617
  • 7
  • 16
  • 36