问题
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says :
TypeError: %d format: a number is required, not str
from sys import argv
file_name, num1, num2 = argv
int(argv[1])
int(argv[2])
def addfunc(num1, num2):
print "This function adds %d and %d" % (num1, num2)
return num1 + num2
addsum = addfunc(num1, num2)
print "The final sum of addfunc is: " + str(addsum)
When I run filename.py 2 2, does argv put 2 2 into strings? If so, how do I convert these into integers?
Thanks for your help.
回答1:
sys.argv
is indeed a list of strings. Use the int()
function to turn a string to a number, provided the string can be converted.
You need to assign the result, however:
num1 = int(argv[1])
num2 = int(argv[2])
or simply use:
num1, num2 = int(num1), int(num2)
You did call int()
but ignored the return value.
回答2:
Assign the converted integers to those variables:
num1 = int(argv[1]) #assign the return int to num1
num2 = int(argv[2])
Doing just:
int(argv[1])
int(argv[2])
won't affect the original items as int
returns a new int
object, the items inside sys.argv
are not affected by that.
Yo modify the original list you can do this:
argv[1:] = [int(x) for x in argv[1:]]
file_name, num1, num2 = argv #now num1 and num2 are going to be integers
回答3:
Running int(argv[1])
doesn't actually change the value of argv[1]
(or of num1
, to which it is assigned).
Replace this:
int(argv[1])
int(argv[2])
With this:
num1 = int(num1)
num2 = int(num2)
and it should work.
The int(..), str(...) etc functions do not modify the values passed to them. Instead, they return a reinterpretation of the data as a different type.
来源:https://stackoverflow.com/questions/17383470/argv-string-into-integer