处理"IndexError: string index out of range"错误



我有以下字符串my_string

my_string = 'A15B27C32D72A7B14C9D31'

我按字符A将此字符串拆分为chunks

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D72', 'A7B14C9D31']

我希望能够检查是否有与每个块的"D"字符关联的数字。 为此,我使用:

for elem in chunks:
if elem[elem.find('D') + 1].isdigit() is False: 
print('no number associated with D')
else:
print('the number associated with D is', elem[elem.find('D') +1])

(从技术上讲,这是不正确的,因为它不会捕获数字不是个位数的情况。

现在,让我们my_string更改为:

my_string = 'A15B27C32DA7B14C9D31'
chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']

(请注意,第一个区块中的D没有关联的编号)

如果我运行以下内容:

for elem in chunks:
if elem[elem.find('D') + 1].isdigit() is False: 
print('no number associated with D')
else:
print('the number associated with D is', elem[elem.find('D') +1])

我得到:

IndexError                                Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_8844/1838165888.py in <module>
1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
3         print('no number associated with D')
4     else:
5         print('the number associated with D is', elem[elem.find('D') +1])
IndexError: string index out of range

要解决此问题,我可以使用try/except.

我还可以使用以下内容:

for elem in chunks:
if elem[-1].isdigit() is False: 
print('no number associated with D')
else:
print('the number associated with D is', elem[elem.find('D') +1])
no number associated with D
the number associated with D is 3

但是,这两种方法都感觉有些笨拙。

有没有更优雅和惯用的方法来处理string index out of range错误?

谢谢!

我会为此建议正则表达式,但逻辑方面,有时边缘情况只需要由您处理

for elem in chunks:
first_d = elem.find('D')
if first_d < len(elem) and elem[first_d + 1].isdigit() is False: 
print('no number associated with D')
else:
print('the number associated with D is', elem[first_d +1])

或者,您可以稍微调整一下逻辑

for elem in chunks:
# should only looks for 'D' from start to second-to-last characters
# because if last character is 'D' it is still not valid
first_d = elem[:-1].find('D')
if elem[first_d + 1].isdigit() is False: 
print('no number associated with D')
else:
print('the number associated with D is', elem[first_d + 1])

>我会再次使用split,并在try/except内进行int转换,以验证D后面的东西是否是一个数字。

>>> my_string = 'A15B27C32D72A7B14C9D31'
>>> for elem in filter(bool, my_string.split("A")):
...     try:
...         print(f"the number associated with D is {int(elem.split('D')[-1])}")
...     except ValueError:
...         print("no number associated with D")
...
the number associated with D is 72
the number associated with D is 31

这是代码

my_string = 'A15B27C32DA7B14C9D31'
chunk = ['A' + elem for elem in s.split('A') if elem != '']
for elem in chunk:
num = elem[(elem.find('D') + 1):]

if num == '' or not num.isdigit():
print('no number associated with D')
else:
print('the number associated with D is', num)

以下是代码中的 4 个问题:

  1. 如果字符串'1234''1234'.find('D')将返回-1'1234'[-1+1]将返回1。这是不正确的
  2. 如果字符串'123D''123D'.find('D')将返回3,这是列表的最后一个元素,因此'123D'[3+1]引发index out of range错误
  3. 如果字符串''''.find('D')将返回-1''[-1+1]→请参见 (2)
  4. 如果字符串'D12D34'→则只会找到第一个D。但据我所知,只有一种D应该通过设计出现在块中

最接近的解决方案是:

d_index = elem.find('D') + 1
if d_index > 0 and len(elem) > d_index and elem[d_index].isdigit() is True:
print('the number associated with D is', elem[elem.find('D') +1])
else:
print('no number associated with D')

相关内容

最新更新