scanf in python
AMD
amdescombes at gmail.com
Sat Jul 26 07:33:09 EDT 2008
Thanks Fredrik,
very nice examples.
André
> AMD wrote:
>
>>> For reading delimited fields in Python, you can use .split string
>>> method.
>
>> Yes, that is what I use right now, but I still have to do the
>> conversion to integers, floats, dates as several separate steps. What
>> is nice about the scanf function is that it is all done on the same
>> step. Exactly like when you use % to format a string and you pass it a
>> dictionary, it does all the conversions to string for you.
>
> You're confusing surface syntax with processing steps. If you want to
> do things on one line, just add a suitable helper to take care of the
> processing. E.g. for whitespace-separated data:
>
> >>> def scan(s, *types):
> ... return tuple(f(v) for (f, v) in zip(types, s.split()))
> ...
> >>> scan("1 2 3", int, int, float)
> (1, 2, 3.0)
>
> This has the additional advantage that it works with any data type that
> provides a way to convert from string to that type, not just a small
> number of built-in types. And you can even pass in your own local
> helper, of course:
>
> >>> def myfactory(n):
> ... return int(n) * "!"
> ...
> >>> scan("1 2 3", int, float, myfactory)
> (1, 2.0, '!!!')
>
> If you're reading multiple columns of the same type, you might as well
> inline the whole thing:
>
> data = map(int, line.split())
>
> For other formats, replace the split with slicing or a regexp. Or use a
> ready-made module; there's hardly every any reason to read standard CSV
> files by hand when you can just do "import csv", for example.
>
> Also note that function *creation* is relatively cheap in Python, and
> since "def" is an executable statement, you can create them pretty much
> anywhere; if you find that need a helper somewhere in your code, just
> put it there. The following is a perfectly valid pattern:
>
> def myfunc(...):
>
> def myhelper(...):
> ...
>
> myhelper(...)
> myhelper(...)
>
> for line in open(file):
> myhelper(...)
>
> (I'd say knowing when and how to abstract things away into a local
> helper is an important step towards full Python fluency -- that is, the
> point where you're able to pack "a lot of action in a small amount of
> clear code" most of the time.)
>
> </F>
>
More information about the Python-list
mailing list