Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sscanf in Python

I'm looking for an equivalent to sscanf() in Python. I want to parse /proc/net/* files, in C I could do something like this:

int matches = sscanf(         buffer,         "%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",         local_addr, &local_port, rem_addr, &rem_port, &inode); 

I thought at first to use str.split, however it doesn't split on the given characters, but the sep string as a whole:

>>> lines = open("/proc/net/dev").readlines() >>> for l in lines[2:]: >>>     cols = l.split(string.whitespace + ":") >>>     print len(cols) 1 

Which should be returning 17, as explained above.

Is there a Python equivalent to sscanf (not RE), or a string splitting function in the standard library that splits on any of a range of characters that I'm not aware of?

like image 809
Matt Joiner Avatar asked Feb 01 '10 06:02

Matt Joiner


People also ask

Is there a scanf () or sscanf () equivalent in python?

Your answerThere is nothing as such for python. For simple input parsing, the easiest way is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float().

How do you write scanf in python?

Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf()format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.

What is used instead of scanf in python?

In python you have to use input() instead of scanf(). In python 2 you can use raw_input().

What does scanf mean in python?

Reading input is handled differently in Python and C: Python uses the input function to read in a value as a string, and then the program converts the string value to an int , whereas C uses scanf to read in an int value and to store it at the location in memory of an int program variable (for example, &num1 ).


1 Answers

There is also the parse module.

parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher).

>>> from parse import parse >>> parse('{} fish', '1') >>> parse('{} fish', '1 fish') <Result ('1',) {}> >>> parse('{} fish', '2 fish') <Result ('2',) {}> >>> parse('{} fish', 'red fish') <Result ('red',) {}> >>> parse('{} fish', 'blue fish') <Result ('blue',) {}> 
like image 184
Craig McQueen Avatar answered Oct 04 '22 21:10

Craig McQueen