如何遍历字符串并打印某些项目? [英] How can I loop through a string and print certain items?

查看:52
本文介绍了如何遍历字符串并打印某些项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lst = 'AB[CD]EF[GH]'

输出:['A','B','CD','E','F','GH']

Output: ['A','B','CD','E','F','GH']

这是我尝试过的方法,但是不起作用...

This is what I've tried but it's not working...

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

有人可以帮忙吗?无需导入正则表达式或其他任何东西.我不想使用它.

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

推荐答案

原始代码的问题似乎是:

The problems with the original code seemed to be:

1)lst,index和multi未初始化

1) lst, index and multi are not initialised

2)循环是无限的,因为循环变量(索引)不会在每次迭代中递增.

2) the loop is infinite because the loop variable (index) isn't incremented on each iteration.

3)检测到右括号时应跳过该括号,以免将其包含在最终列表中

3) the close bracket needs to be skipped when detected to avoid including it in the final list

此代码是如何解决这些问题的示例:

This code is an example of how to fix those issues:

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]'))

这篇关于如何遍历字符串并打印某些项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆