scanf in python...?
Andrew Dalke
dalke at acm.org
Wed Oct 18 01:57:50 EDT 2000
Tony Waterman wrote in message <39ebd839.159714 at news>...
>Does python have any way to mimic scanf ?
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.033.htp
=========
Python FAQ Entry
4.33. Is there a scanf() or sscanf() equivalent?
Not as such.
For simple input parsing, the easiest approach is usually to split the line
into whitespace-delimited words using string.split(), and to convert decimal
strings to numeric values using string.atoi(), string.atol() or
string.atof(). (Python's atoi() is 32-bit and its atol() is arbitrary
precision.) If you want to use another delimiter than whitespace, use
string.splitfield() (possibly combining it with string.strip() which removes
surrounding whitespace from a string).
For more complicated input parsing, regular expressions (see module re) are
better suited and more powerful than C's sscanf().
There's a contributed module that emulates sscanf(), by Steve Clift; see
contrib/Misc/sscanfmodule.c of the ftp site:
http://www.python.org/ftp/python/contrib-09-Dec-1999/Misc/
=========
Hmmm, isn't "splitfield" deprecated? Just fixed the FAQ.
Andrew
dalke at acm.org
More information about the Python-list
mailing list