Hsun-Yi Hsieh Hsun-Yi Hsieh - 4 months ago 8
Python Question

formatting the return in python - print out different types of values

I have the following code

$ipython
> import csv
> with open('q1_4.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
for row in reader:
print [tuple(row)]


In each row, I have four values, each of which is a string, a number, a number and a number. How could I print out "string", num, num, num for each row, instead of "string", "string", "string", "string"?

Answer

If formatting is all you are concerned about

with open('q1_4.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
    for row in reader:
        print '"{}", {}, {}, {}'.format(*row)

Test:

>>> row = ["string", "1", "2", "3"]
>>> print '"{}", {}, {}, {}'.format(*row)
"string", 1, 2, 3

Update per your request in the comments. Here are several options you can use to return a tuple

return (row[0],) + tuple(int(n) for n in row[1:])  # Python 2 and 3
return (row[0],) + tuple(map(int, row[1:]))  # Python 2 and 3
return tuple(chain([row[0]], map(int, row[1:]))) # Python 2 and 3; requires importing `chain` from `itertools`

Though I prefer Python 3 here:

return (row[0], *map(int, row[1:]))  # Python 3 only

If you want to return a list of tuples, take any of that constructs (I'll pick the third one for brevity) and do:

return [(row[0], *map(int, row[1:])) for row in reader]

NOTE You can only return from a function, so you'll have to wrap it all into a function.