0

当我用分隔符分割字符串时,我需要检查存在的元素数量。

>>> 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-exceptif-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"
4

2 回答 2

3

您可以使用以下方法计算分隔符str.count

>>> "12342foo \t62 bar sd\t\7534 black sheep".count('\t') == 4 - 1
False
>>> "12342foo \t62 bar sd\t\7534 black\tsheep".count('\t') == 4 - 1
True

x = "12342foo \t62 bar sd\t\7534 black sheep"
if x.count('\t') == 4 - 1:
    a, b, c, d = x.split('\t')

顺便说一句,我会使用try ... except ValueError.

于 2013-10-16T07:57:07.580 回答
0

您还可以尝试获取由以下生成的列表的长度split

>>> x = "12342foo \t62 bar sd\t\7534 black sheep"
>>> len(x.split('\t'))
4
于 2013-10-16T08:20:58.307 回答