【问题标题】:IndexOutOfBound and storing with comma splitIndexOutOfBound 并用逗号分隔存储
【发布时间】:2019-10-25 06:47:39
【问题描述】:

如果字符串遵循这种格式,例如'a,b,c,d'(其中abcd 都是int)或完全为空。 例如:

179,170,271,83
null
143,406,299,44
145,403,299,44
142,404,299,44

31,450,337,36

null

90,269,242,32
87,266,244,35
null
272,251,223,119
27,40,316,10

如何存储a,b,c,d 的值?

我尝试使用分隔逗号并检查空字符串,但没有帮助

if string:
      txt = string.split(',')
      height = txt[0]
      left = txt[1]
      top = txt[2]
      width = txt[3]
else:
      height = ""
      left = ""
      top = ""
      width = ""

【问题讨论】:

  • 您如何阅读您的输入?您可以从输入中发布非空字符串和空字符串的示例吗?
  • 你真的有空行以及包含字符串null的行吗?

标签: python indexoutofboundsexception


【解决方案1】:

在 Python 中,在这种情况下使用 try/except 而不是首先进行测试是很常见的。这通常称为asking for forgiveness not permission。为此,您可以将预期的情况包装在 try 中,并将边缘情况设置为 except:

def printDims(s):
    try:
        height, left, top, width = s.split(',')
    except ValueError:
         height, left, top, width = [''] * 4
    finally:
        print(height, left, top, width)


printDims("1,2,3,4") # prints 1, 2, 3, 4
printDims("")        # prints the empty strings

【讨论】:

  • 我会调查的。 ty :)
【解决方案2】:

查看txt的长度:

if string:
    txt = string.split(',')
    if len(txt) == 4:
        height = txt[0]
        left = txt[1]
        top = txt[2]
        width = txt[3]
    else:
        height = ""
        left = ""
        top = ""
        width = ""
else:
    height = ""
    left = ""
    top = ""
    width = ""

【讨论】:

  • 非常感谢,效果很好!我想我没有检查长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多