28

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] ...
1
  • Do you mean string is empty(means string of length zero) or None ? Commented Aug 31, 2009 at 11:09

3 Answers 3

90
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"]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
13
a = '0' if not line_parts[0] else line_parts[0]

1 Comment

Would be more clear as: a = line_parts[0] if line_parts[0] else '0'
0

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.