Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Python implementation of nextInt(), hasNext() from Java?

Tags:

java

python

I have this input file

1 2
10 2
81 3
23 6
2537857295 19
34271891003654321 1267253

I am reading the file like this

with open("powersearch.txt") as fileIn:
    for line in fileIn:
        print line

I am wondering if I want to, for every single line, have the 1st integer stored as firstNum, the 2nd stored as secondNum. With Java I can use a scanner and do nextInt() and hasNext() to get the integers, what are the equivalent in Python?

like image 862
Tu Hoang Avatar asked Dec 07 '22 19:12

Tu Hoang


1 Answers

Well to parse an int from a string you just use int(s), where s is the string.

I think this would be the most logic way in your example:

with open("powersearch.txt") as fileIn:
    for line in fileIn:
        n1, n2 = (int(s) for s in line.split())
        print(n1, n2)

Python is a different language than Java, and in my opinion more expressive (I can do more in one line than I can in Java and still write readable code). If you try to write Java stuff in Python you'll find the language a lot less effective than it can be.

like image 107
orlp Avatar answered Dec 10 '22 13:12

orlp