lst = 'AB[CD]EF[GH]'
输出:['A','B','CD','E','F','GH']
这是我尝试过的,但它不起作用......
while(index < len(my_string)):
curr_char = my_string[index]
if(curr_char == '['):
while(curr_char != ']'):
multi = my_string[index + 1]
index += 1
lst += multi
有人可以帮忙吗?无需导入正则表达式或其他内容。我想在不使用它的情况下做到这一点。
原始代码的问题似乎是:
1)lst、index、multi未初始化
2) 循环是无限的,因为循环变量(索引)不会在每次迭代时递增。
3)检测到时需要跳过右括号以避免将其包含在最终列表中
此代码是如何解决这些问题的示例:
def getList(s):
outList=[]
lIndex=0
while lIndex < len(s):
if s[lIndex] == "[":
letters=""
lIndex+=1
while s[lIndex] != "]":
letters+=s[lIndex]
lIndex+=1
outList.append(letters)
else:
outList.append(s[lIndex])
lIndex+=1
return outList
print(getList('AB[CD]EF[GH]'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)