Python Argv - 字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17383470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:03:45  来源:igfitidea点击:

Argv - String into Integer

pythonargv

提问by Andrew Blanchette

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 :

我在 python 方面很新,我一直在玩 argv。我在这里编写了这个简单的程序并收到一个错误消息:

TypeError: %d format: a number is required, not str

类型错误:%d 格式:需要一个数字,而不是 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?

当我运行 filename.py 2 2 时,argv 是否将 2 2 放入字符串中?如果是这样,我如何将这些转换为整数?

Thanks for your help.

谢谢你的帮助。

采纳答案by Martijn Pieters

sys.argvis indeed a list of strings. Use the int()function to turn a string to a number, provided the string canbe converted.

sys.argv确实是一个字符串列表。使用该int()函数将字符串转换为数字,前提是该字符串可以转换。

You need to assignthe 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.

您确实调用了int()但忽略了返回值。

回答by Ashwini Chaudhary

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 intreturns a new intobject, the items inside sys.argvare not affected by that.

不会影响原始项目,因为int返回一个新int对象,里面的项目sys.argv不受此影响。

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

回答by J David Smith

Running int(argv[1])doesn't actually change the value of argv[1](or of num1, to which it is assigned).

运行int(argv[1])实际上并没有改变argv[1](或 of num1,它被分配到) 的值。

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 returna reinterpretation of the data as a different type.

int(..)、str(...) 等函数不会修改传递给它们的值。相反,它们将数据的重新解释返回为不同的类型。