ValueError:也可以解压缩值

时间:2014-04-05 16:10:02

标签: python

请问有人对此提出一些意见。

for line in oscars_file:
    if '-' in line:
        years,oscars=line.strip().split('-')

我在终端收到此错误:

ValueError: too many values to unpack (expected 2)

oscars文件的一个例子是:

1975 - "One Flew over the Cuckoo's Nest"

1973 - "The Sting"

1 个答案:

答案 0 :(得分:4)

您的部分文字可能包含多个'-'。为此,你应该这样做:

for line in oscars_file:
    if '-' in line:
        years,oscars=line.strip().split('-',1)

split('-',1)只进行一次分割,这是您想要的第一次分割。

实施例

>>> s = '1-2-3-4'
>>> print s.split('-',1)
['1','2-3-4']
>>> print s.split('-',2)
['1','2','3-4']