tags:

views:

321

answers:

3

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] ...
+6  A: 
a = '0' if not line_parts[0] else line_parts[0]
Andrew Keeton
Would be more clear as: a = line_parts[0] if line_parts[0] else '0'
recursive
+19  A: 
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"]
Ned Batchelder
+1 I learned something new.
Andrew Keeton
To clarify, if it wasn't clear from Ned's answer: when it comes to strings, an empty string always evaluates to False, and a non-empty string always evaluates to True -- that's why `or` works perfectly in this situation.
Mark Rushakoff
When using this, make sure that you never expect `arg2` to be 0 or ''..
John Fouhy
I don't understand - what the difference then to give a default value in a definition of a function: def fn(arg1, arg2="weird default value"): ?
You can do that, but have to be careful with mutable defaults, or defaults based on changing data that may not be available at definition time.
Ned Batchelder
A: 

Do you mean string is empty(means string of length zero) or None ?

Manish Sinha
comments belong to comments.
SilentGhost