4

As you know over Python 3.6, there is a feature known as format string literals. str(obj['my_str_index']) can be either None or a string value. I've tried the below one but it doesn't yield 'null' text if it is None.

foo = "soner test " \
f"{str(obj['my_str_index']) if str(obj['my_str_index']) is not None else 'null'}
snr
  • 16,197
  • 2
  • 61
  • 88
  • Does this answer your question? [Using f-string with format depending on a condition](https://stackoverflow.com/questions/51885913/using-f-string-with-format-depending-on-a-condition) – clubby789 Jan 15 '20 at 11:08
  • @JammyDodger it is what actually tried but it doesn't yield my wish. Thanks for your help by the bye. – snr Jan 15 '20 at 11:09
  • 2
    Do you absolutely need to do it this way? it's borderlining abusing the f-string mechanism. I think an explicit if condition will be much more readable – DeepSpace Jan 15 '20 at 11:10
  • @DeepSpace highly likely in future nobody needs to touch the code, that is, it can be considered as just two-click script. – snr Jan 15 '20 at 11:11

2 Answers2

4

str(None) is not None, but "None". So without that useless and harmful stringification:

foo = "soner test " \
f"{str(obj['my_str_index']) if obj['my_str_index'] is not None else 'null'}"

EDIT: A more legible way (note that interpolation in an f-string automatically stringifies, so we don't need str at all):

index = obj['my_str_index']
if index is None:
    index = "none"
foo = f"soner test {index}"

EDIT: Another way, with the walrus (limited to 3.8+):

foo = f"soner test {'null' if (index := obj['my_str_index']) is None else index}"
Amadan
  • 179,482
  • 20
  • 216
  • 275
2

You can greatly simplify the condition. This will work (in most cases, see the caveat below) and in my opinion a bit more readable

foo = f"soner test {obj['my_str_index'] or 'null'}"

You don't have to worry about str(...) because the interpolation mechanism calls the objects __str__ method implicitly (if it does not have __format__).

The only caveat with this approach is that foo will contain null if obj['my_str_index'] is any of the falsey values (None, 0 and any empty sequence).

DeepSpace
  • 72,713
  • 11
  • 96
  • 140