Neil G
Neil G

Reputation: 33202

How do I read the next integer ignoring whitespace in Python?

How do I read the next integer ignoring whitespace in Python 3? Is there a way to make a generator that returns integers from a stream of whitespace-separated integers?

The best I have is this:

def ints():
    while True:
        yield from (int(x) for x in input().split())

Upvotes: 1

Views: 3367

Answers (2)

dawg
dawg

Reputation: 103814

If you are reading from stdin, you can do this:

import sys

def ints():
    for line in sys.stdin:
        rtr=[int(d) for d in line.split() if d.isdigit()] 
        if rtr:
            for n in rtr:
                yield n

print(list(ints()))

Or, if your Py 3.3+ supports generator delegation:

import sys

def ints():
    for line in sys.stdin:
         yield from (int(d) for d in line.split() if d.isdigit())

You can also use the very slick fileinput which has the advantage of supporting both a file name (and the file by that name will then be opened and read) or input from the redirected stdin:

import fileinput

def ints():
    for line in fileinput.input():
        yield from (int(d) for d in line.split() if d.isdigit())

(If you test fileinput directly or manually, know that you need to end the input with two CtlD's -- not just one....)

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142136

Complete ignoring white space and reading from a file (treating an integer purely as consecutive digits):

import mmap
import re

with open('somefile', 'rb') as fin:
    mf = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
    for digits in re.finditer('(\d+)', mf):
        print(digits.group(1))

Or, if you've already got everything in a string, then adapt the finditer appropriately, maybe something like:

yield from (match.group(1) for match in re.finditer('\d+', some_string))

Upvotes: 3

Related Questions