I have a parsing system for fixed-length text records based on a layout table:
parse_table = [\\
(\'name\', type, length),
....
(\'numeric_field\
Use a factory function instead of int or a subclass of int:
def mk_int(s):
s = s.strip()
return int(s) if s else 0
Use int()
function with the argument s.strip() or 0
, i.e:
int(s.strip() or 0)
Or if you know that the string will always contain only digit characters or is empty (""
), then just:
int(s or 0)
lenient_int = lambda string: int(string) if string.strip() else None
#else 0
#else ???
note that mylist is a list that contain:
Tuples, and inside tuples, there are I) null / empty values, ii) digits, numbers as strings, as well iii) empty / null lists. for example:
mylist=[('','1',[]),('',[],2)]
@Arlaharen I am repeating here, your solution, somewhat differently, in order to add keywords, because, i lost a lot of time, in order to find it!
The following solution is stripping / converting null strings, empty strings, or otherwise, empty lists, as zero, BUT keeping non empty strings, non empty lists, that include digits / numbers as strings, and then it convert these strings, as numbers / digits.
Simple solution. Note that "0" can be replaced by iterable variables. Note the first solution cannot TREAT empty lists inside tuples.
int(mylist[0][0]) if mylist[0][0].strip() else 0
I found even more simpler way, that IT can treat empty lists in a tuple
int(mylist[0][0] or '0')
convert string to digits / convert string to number / convert string to integer strip empty lists / strip empty string / treat empty string as digit / number convert null string as digit / number / convert null string as integer