当我用分隔符分割字符串时,我需要检查存在的元素数量。
>>> x = "12342foo \t62 bar sd\t\7534 black sheep"
>>> a,b,c = x.split('\t')
>>> a,b,c,d = x.split('\t')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
除了try-except
和if-else
条件(见下文),我还能如何检查分隔字符串是否有 X 个元素?
>>> try:
>>> a,b,c,d = x.split('\t')
>>> except:
>>> raise KeyError('You need 4 elements after splitting the string')
>>> if len(x.split('\t')) == 4:
>>> a,b,c,d = x.split('\t')
>>> else:
>>> print "You need 4 elements after splitting the string"