문제

Let's say you have input (command line arguments, txt file) that consists of multiple datatypes, like int and str. How can you efficiently turn each item into int if its a number, and str if its a str?

Example:

input.txt

A 1 B C 23 
5 D 0 E 2
143 E 6 A 1

output:

["A",1,"B","C",23]
[5,"D",0,"E",2]
[143,"E",6,"A",1]

Using open() and readlines(), you can store it in a variable and get:

['A 1 B C 23 \n', '5 D 0 E 2\n', '143 E 6 A 1']

But from here, if I want to use strip, I have to specify whether I want to convert everything to str() or int()- int() will cause error because it can't accept strings, and str() will just convert everything to string.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top