6

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'}
4
  • Does this answer your question? Using f-string with format depending on a condition Commented Jan 15, 2020 at 11:08
  • @JammyDodger it is what actually tried but it doesn't yield my wish. Thanks for your help by the bye. Commented Jan 15, 2020 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 Commented Jan 15, 2020 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. Commented Jan 15, 2020 at 11:11

2 Answers 2

5

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}"
Sign up to request clarification or add additional context in comments.

6 Comments

Now combine it with Python 3.8's walrus operator so obj['my_str_index'] is not evaluated twice... 🤔
@DeepSpace Oh, I was not even close to arguing that this is the best way to do this. :)
@Armadan if you have better idea, you can post it sir. I can learn ((:
@DeepSpace if you think there is a better way, I'm very glad to learn, thanks.
index = obj['my_str_index'] or "none"
|
5

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).

1 Comment

Finally, for the multiple line string: foo = ( f"soner test " f"{obj['my_str_index'] or 'null'}" )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.