试图找到所有出现的字符
string1 = '%(example_1).40s-%(example-2)_-%(example3)s_'
Run Code Online (Sandbox Code Playgroud)
所以输出中出现的所有' - ''_'都不在括号中
['-', '_', '-', '_']
Run Code Online (Sandbox Code Playgroud)
不需要关心嵌套括号
您可以使用模块re通过将正则表达式传递给它来执行此操作
import re
str = '%(example_1).40s-%(example-2)_-%(example3)s_'
#remove all occurences of paratheses and what is inside
tmpStr = re.sub('\(([^\)]+)\)', '', str)
#take out other element except your caracters
tmpStr = re.sub('[^_-]', '', tmpStr)
#and transform it to list
result_list = list(tmpStr)
Run Code Online (Sandbox Code Playgroud)
结果
['-', '_', '-', '_']
Run Code Online (Sandbox Code Playgroud)
就像Bharath shetty在评论中提到的那样,不要使用str,它是python中内置字符串的保留字
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |