A small scanf implementation
Python has powerful regular expressions but they can be totally overkill for many simpler situations. Additionally, some common numerical formats require quite complex regex’s to match them robustly. This python implementation of scanf internally translates the simple scanf format into regular expressions, then returns the parsed values.
scanf.scanf(format, s=None, collapseWhitespace=True)
scanf supports the following formats:
|%d, %i||int value|
|%7d, %7i||int value with length 7|
|%X, %x||hex value|
|%s||string terminated by whitespace|
Any pattern with a * after the % (e.g., ‘%*f’) will result in scanf matching the pattern but omitting the matched portion from the results. This is helpful when parts of the input string may change but should be ignored.
The underlying regex operation is performed using ‘search’ rather than ‘match’, so scanf will return a match if the pattern string is matched anywhere in the line.
>>> from scanf import scanf >>> scanf("%s - %d errors, %d warnings", "/usr/sbin/sendmail - 0 errors, 4 warnings") ('/usr/sbin/sendmail', 0, 4)
>>> scanf("%o %x %d", "0123 0x123 123") (66, 291, 123)
>>> pattern = 'Power: %f [%], %s, Stemp: %f' >>> text = 'Power: 0.0 [%], Cool, Stemp: 23.73' >>> scanf(pattern, text) (0.0, 'Cool', 23.73)
>>> pattern = 'Power: %f [%], %*s, Stemp: %f' # note the '*' in %*s >>> scanf(pattern, text) (0.0, 23.73)
scanf returns a tuple of parsed values if the input pattern is matched, or None if the format does not match.
For more information see:
Original code from: http://code.activestate.com/recipes/502213-simple-scanf-implementation/
Modified original to make the %f more robust, as well as added %* modifier to skip fields.
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|File Name & Checksum SHA256 Checksum Help||Version||File Type||Upload Date|
|scanf-1.4.1-py2.py3-none-any.whl (7.8 kB) Copy SHA256 Checksum SHA256||py2.py3||Wheel||Apr 5, 2017|
|scanf-1.4.1.tar.gz (5.0 kB) Copy SHA256 Checksum SHA256||–||Source||Apr 5, 2017|