Scan until random delimiter.

Laurent Verweijen somelauw at gmail.com
Sun Jun 27 16:41:51 EDT 2010


In contrast to java or c python seems not be able to use a random
delimiter.

In java, you can do:


Code:

import java.util.Scanner

Scanner sc = new Scanner(System.in).useSeperator(" ")
int a = sc.nextInt()


But in python there seems to be no other option then waiting until you
see a newline.
I wrote a script which should allow more freedom.


Code:

#!/usr/bin/python

def readtoken(source=None, delim=" \n\t\r"):
        if source is None:
                from sys import stdin
                source = stdin

        r = []
        c = delim + " "

        while c not in delim:
                c = source.read(1)
                r.append(c)

        return "".join(r)

if __name__ == "__main__":
        for _ in range(5):
                print(readtoken())


It works a bit but still requires the user to press enter.
Is there some way around it, which is platform independant? 




More information about the Python-list mailing list