scanf in python...?

Greg Jorgensen gregj at pobox.com
Tue Oct 17 01:53:46 EDT 2000


"Tony Waterman" <tonyw54 at home.com> wrote in message
news:39ebd839.159714 at news...
> Does python have any way to mimic scanf ? I just bought Python on
> Win32 and I can't find anything in there about it, or on the
> python.org html tutorial. Also; how many ways to mimic scanf are
> there?

scanf is necessary in C because C is a statically-typed language. Python is
dynamically typed--names can represent any type and change type at runtime.

You can use Pythons string functions and conversions to accomplish what you
would do with scanf in C:

# assume input lines: lastname firstname salary
total = 0.0
while 1:
    s = sys.stdin.readline()
    if not s:
        break
    t = s.split()    # break s on whitespace into list of three elements
    total += float(t[2])    # convert salary to float, add to total
    ...

This technique will work with simple delimited input lines. You can handle
almost anything with regular expressions.

--
Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com





More information about the Python-list mailing list