Home > database >  How to use rsplit with None vaules in Python?
How to use rsplit with None vaules in Python?

Time:06-01

At my Python application, I want to get a specific value from a list:

rating_unit_value = clean_result['format']['tags'].get('itunextc', None).rsplit('|', 3)[0]

The Problem here is that if 'itunextc' does not exist, it should return None instead, where rsplit can't work with a None value. So, how can I apply the rsplit only if 'itunextc' exists? Of course this can be done with an if else statement or try except, but is this really the only way to go ?

Something like this pseudocode would be cool:

rating_unit_value = clean_result['format']['tags'].get('itunextc'.rsplit('|', 3)[0], None)

Thanks in advance.

CodePudding user response:

Using an assignment expression and a conditional expression:

rating_unit_value = val.rsplit('|', 3)[0] if (val := clean_result['format']['tags'].get('itunextc')) else None

Whether that is clearer (or generally "better") than an if-else or a try-except, is really in the eye of the beholder.


Simplified example:

>>> a = dict(b='1|1')
>>> e = val.split('|') if (val := a.get('c')) else None
>>> print(e)
None
>>> e = val.split('|') if (val := a.get('b')) else None
>>> e
['1', '1']
  • Related