Is it possible to unpack a tuple replacing missing elements with None in python?

Viewed 36

I'm wondering if there is a way in python to unpack a tuple replacing missing elements with None. Here is an example:

username, password = credentials.split(':', maxsplit=1)

For the credentials equal to root:123456 it returns ('root', '123456') as expected. But for credentials equal to root it throws an exception ValueError: not enough values to unpack (expected 2, got 1) as expected as well, but not as I want. I want it to return ('root', None) instead. Do you know how to do that?

I could do it like this:

credentials_split = credentials.split(':', maxsplit=1)
username, password = credentials_split[0], credentials_split[1] if len(credentials_split) > 1 else None

But it's ugly, I'm looking for a better solution. Thanks in advance!

0 Answers
Related