IndexOutOfBound 并以逗号分隔存储
IndexOutOfBound and storing with comma split
如果一个字符串要么遵循这种格式,例如'a,b,c,d'
(其中a
、b
、c
、d
都是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 = ""
在 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
检查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 = ""
如果一个字符串要么遵循这种格式,例如'a,b,c,d'
(其中a
、b
、c
、d
都是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 = ""
在 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
检查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 = ""