Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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] ...
like image 1000
biznez Avatar asked Sep 06 '25 09:09

biznez


2 Answers

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"]
like image 78
Ned Batchelder Avatar answered Sep 08 '25 12:09

Ned Batchelder


a = '0' if not line_parts[0] else line_parts[0]
like image 31
Andrew Keeton Avatar answered Sep 08 '25 11:09

Andrew Keeton