在python中接受逗号分隔的数字和拆分空格

2024-09-28 05:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试接受一个由逗号分隔的整数序列,并希望修剪随它而来的任何空格。我正在使用下面的代码。你知道吗

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溶液:)


Tags: 代码ininputissomeareintsplit
2条回答

Python 3.6版

values = input("Input some comma seprated numbers : ")
print("Values are :", values) #Output: 1,2 3,4

val = ",".join(values.split(" "))
print("Values seperated with comma :", val) #Output: 1,2,3,4

a = val.split(',')
print("a is", a) #Output: a is ['1', '2', '3', '4']

示例输出与您提供的snipplet不匹配,因为错误行是a = int(Arr)。在示例代码中,在Arr上还有一个split(),它应该引发一个AttributeError,因为Arr已经是一个列表了。你知道吗

要删除字符串开头/结尾的空白,请使用^{}方法:

l = values.split(",")
a = [int(x.strip()) for x in l]

如果数组包含无法转换为整数的字符串(包括数字之间有空格),则会引发ValueError。你知道吗

如果您想删除所有的空白,包括数字之间的空白(将“1 2 3”变成“123”),您可以使用类似的方法:

l = "".join(values.split())
a = [int(x.strip()) for x in l.split(",")]

相关问题 更多 >

    热门问题