我正在尝试接受一个由逗号分隔的整数序列,并希望修剪随它而来的任何空格。我正在使用下面的代码。你知道吗
values = raw_input("Input some comma seprated numbers : ")
print "Values are", values
Arr = values.split(",")
print "Arr is", Arr
a = [int(x) for x in Arr.split()]
print "a is", a
在执行上述代码段时,出现以下异常:
$ python accept.py
Input some comma seprated numbers : 1,3, 2
Values are 1,3, 2
Arr is ['1', '3', ' 2']
Traceback (most recent call last):
File "accept.py", line 20, in <module>
a = int(Arr)
TypeError: int() argument must be a string or a number, not 'list'
如果输入1、3、2或1、3、2,我可以通过修改代码来成功。但如果我把两者都混在一起,问题就来了。你知道吗
使用Python版本2。(不介意Python3溶液:)
Python 3.6版
示例输出与您提供的snipplet不匹配,因为错误行是
a = int(Arr)
。在示例代码中,在Arr
上还有一个split()
,它应该引发一个AttributeError
,因为Arr
已经是一个列表了。你知道吗要删除字符串开头/结尾的空白,请使用^{} 方法:
如果数组包含无法转换为整数的字符串(包括数字之间有空格),则会引发
ValueError
。你知道吗如果您想删除所有的空白,包括数字之间的空白(将“1 2 3”变成“123”),您可以使用类似的方法:
相关问题 更多 >
编程相关推荐