One option is to use exception handling:
import sys
def strint (s):
try:
x = int(s)
except:
x = s
return x
for line in sys.stdin:
print([strint(x) for x in line.split()])
With the above code in strint.py
and the example input in the file strint.txt
, we can run it to get the following output:
$ python strint.py <strint.txt
['A', 1, 'B', 'C', 23]
[5, 'D', 0, 'E', 2]
[143, 'E', 6, 'A', 1]
A more sophisticated version would catch the specific exceptions and could deal with floating point numbers, etc.