如何检查分隔的字符串是否有X个元素?蟒蛇

时间:2013-10-16 07:54:47

标签: python string try-catch delimiter

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您还可以尝试使用split生成的列表的长度:

>>> x = "12342foo \t62 bar sd\t\7534 black sheep"
>>> len(x.split('\t'))
4