user7500570
user7500570

Reputation:

Optional string format

Is it possible to improve this code:

if isinstance(value, bool) and value:
    cms = "%s %s" % (cms, usage_map["switches"][switch])
else:
    cms = "%s %s %s" % (cms, usage_map["switches"][switch], value)

To use in just one line? Making the value optional?

Thanks!

Upvotes: 0

Views: 151

Answers (2)

SylvainD
SylvainD

Reputation: 1761

You could write:

cms = "%s %s" % (cms, usage_map["switches"][switch])
if isinstance(value, bool) and value:
    cms += " %s" % value

Also, I think you could rewrite the condition as: if value is True:.

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69923

You can use this:

cms = '{} {}{}'.format(
    cms, usage_map["switches"][switch],
    '' if isinstance(value, bool) and value else ' {}'.format(value)
)

Upvotes: 2

Related Questions