Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert empty string to zero

I'm doing something like this to sum up all values from start to end.

big_list = line.split(delim)
sum( [int(float(item)) for item in big_list[start:end]] )

Sometimes an element of big_list may be empty, in which case the conversion fails. Can I make it work with empty strings in an elegant way, without changing too much above?

like image 666
Bob Avatar asked Dec 30 '25 18:12

Bob


1 Answers

Assuming that empty elements should be zero:

sum(int(float(item)) for item in big_list[start:end] if item)
                                                   # ^ skip over ""

Note that:

  1. sum can take the generator expression as an argument, there's no need to build the list; and
  2. An empty string "" evaluates False-y, so this is equivalent to if item != "".
like image 80
jonrsharpe Avatar answered Jan 04 '26 22:01

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!