Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "int" parse blank strings?

Tags:

python

I have a parsing system for fixed-length text records based on a layout table:

parse_table = [\     ('name', type, length),     ....     ('numeric_field', int, 10), # int example     ('textc_field', str, 100), # string example     ... ] 

The idea is that given a table for a message type, I just go through the string, and reconstruct a dictionary out of it, according to entries in the table.

Now, I can handle strings and proper integers, but int() will not parse all-spaces fields (for a good reason, of course).

I wanted to handle it by defining a subclass of int that handles blank strings. This way I could go and change the type of appropriate table entries without introducing additional kludges in the parsing code (like filters), and it would "just work".

But I can't figure out how to override the constructor of a build-in type in a sub-type, as defining constructor in the subclass does not seem to help. I feel I'm missing something fundamental here about how Python built-in types work.

How should I approach this? I'm also open to alternatives that don't add too much complexity.

like image 459
Alex B Avatar asked May 31 '10 06:05

Alex B


People also ask

How do I convert a string to an empty number?

Multiplying a string by 1 ( [string] * 1 ) works just like the unary plus operator above, it converts the string to an integer or floating point number, or returns NaN (Not a Number) if the input value doesn't represent a number. Like the Number() function, it returns zero ( 0 ) for an empty string ( '' * 1 ).

What is parseInt of empty string?

If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().

How do I parse a string to a nullable int?

To parse a string into a nullable int we can use the int. TryParse() method in c#.

How do you convert an empty string to an int in Python?

To convert a string to an integer you use the handy int() function. For example, if you have a string such as "79" and you insert this like so into the int() function: int("79") you get the result 79 .


1 Answers

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 
like image 113
Arlaharen Avatar answered Sep 20 '22 13:09

Arlaharen