-2

one step further than How to implement conditional string formatting?

Basically: is it possible to add if, elif.... else in a format string?

l = ['it', 'en', 'es']

for i in l:
    print('{tit}'.format(tit='Ciao' if i == 'it' elif i == 'en' tit='Hi' else 'Hola'))
matteo
  • 4,683
  • 9
  • 41
  • 77
  • 3
    This would make a lot more sense as `{'it': 'Ciao', 'en': ...}`. While it's possible to have inline `if` expressions, which you could even chain to emulate something like `elif`, it's an insane an unmaintainable structure. – deceze Mar 20 '19 at 08:04
  • the general workflow I have is more complex to have a single dictionary like you suggested. Why is it insane? – matteo Mar 20 '19 at 08:06
  • If your workflow is so complex, why do you want to do all of it in a single line? – Aran-Fey Mar 20 '19 at 08:08
  • 1
    Just look at it, it's unreadable (and the actual working equivalent wouldn't be much better). Also, every time you may add one more item to `l`, you need to keep adding to that already unreadable expression everywhere you use such a thing in your code. That's why it's much better to define something like a dict upfront where the data which belongs together is defined together, and the rest is a generic algorithm which doesn't need to be hardcoded to `if i == 'it' …`. Even if your actual case is more complex, there *are* certainly solutions that follow this better pattern. – deceze Mar 20 '19 at 08:09
  • ok then I'll refactor the code. Thanks for the suggestions – matteo Mar 20 '19 at 08:11

2 Answers2

1

Author of the questions asks if it is possible to add if, elif, else in string formating. So, I do assume author wants to change the value of the string depending on some condition but wants to use if, elif, else for some reasons.

Here is my answer:

t = ['Ciao' if x == 'it' else ('Hi' if x == 'en' else 'Hola') for x in ['it', 'en', 'es']]

I personally do not like if, elif, else logic in such case.

naivepredictor
  • 898
  • 4
  • 14
1

Although I would not recommend it - to answer the question:

It is not possible to use elif in a format string.

It is however possible to use nested conditional expressions:

l = ['it', 'en', 'es']

for i in l:
    print('{tit}'.format(tit=('Ciao' if i == 'it' else 'Hi' if i == 'en' else 'Hola')))

outputs:

Ciao
Hi
Hola

see https://docs.python.org/3/reference/expressions.html#conditional-expressions

Cloudomation
  • 1,597
  • 1
  • 6
  • 15