How to simulate scanf() method using Python?

According to Python documentation

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.

scanf() TokenRegular Expression

%e, %E, %f, %g
%x, %X

To extract the filename and numbers from a string like

/usr/sbin/sendmail - 0 errors, 4 warnings

you would use a scanf() format like

%s - %d errors, %d warnings

The equivalent regular expression would be

(\S+) - (\d+) errors, (\d+) warnings

Updated on: 02-Nov-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started