【问题标题】:How to check that the delimited string has X number of elements? python如何检查分隔字符串是否有 X 个元素? Python
【发布时间】:2013-10-16 07:54:46
【问题描述】:

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

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

【问题讨论】:

  • try-except 和 if-else 有什么问题?

标签: python string try-catch delimiter


【解决方案1】:

您可以使用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?
  • @alvas,因为n 分隔符将生成n + 1 项目。
【解决方案2】:

也可以尝试取split产生的列表长度:

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

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2014-09-19
    • 1970-01-01
    • 2011-01-31
    • 2011-12-11
    • 2019-09-20
    • 1970-01-01
    • 2014-06-23
    • 2019-10-22
    相关资源
    最近更新 更多