biznez
biznez

Reputation: 4021

One-liner Python code for setting string to 0 string if empty

What is a one-liner code for setting a string in python to the string, 0 if the string is empty?

# line_parts[0] can be empty
# if so, set a to the string, 0
# one-liner solution should be part of the following line of code if possible
a = line_parts[0] ...

Upvotes: 28

Views: 27252

Answers (3)

Kannan Ramamoorthy
Kannan Ramamoorthy

Reputation: 4180

If you would also like to consider the white spaces as empty and get the result stripping of those, the below code will help,

a = (line_parts[0] and line_parts[0].strip()) or "0"

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375634

a = line_parts[0] or "0"

This is one of the nicest Python idioms, making it easy to provide default values. It's often used like this for default values of functions:

def fn(arg1, arg2=None):
    arg2 = arg2 or ["weird default value"]

Upvotes: 90

Andrew Keeton
Andrew Keeton

Reputation: 23321

a = '0' if not line_parts[0] else line_parts[0]

Upvotes: 13

Related Questions