[英]How to extract various parts of a string into separate strings
I am trying to make a function to help me debug. 我正在尝试创建一个函数来帮助我调试。 When I do the following:
当我执行以下操作时:
s = traceback.format_stack()[-2]
print(s)
I get a console output something like: 我得到一个控制台输出类似于:
File "/home/path/to/dir/filename.py", line 888, in function_name
How can I extract filename.py
, 888
and function_name
into separate strings? 如何将
filename.py
, 888
和function_name
提取到单独的字符串中? Using a regex? 使用正则表达式?
You can try to use str.split(): 您可以尝试使用str.split():
>>> s = 'File "/home/path/to/dir/filename.py", line 888, in function_name'
>>> lst = s.split(',')
>>> lst
['File "/home/path/to/dir/filename.py"', ' line 888', ' in function_name']
so for the 888 and function_name, you can access them like this 所以对于888和function_name,您可以像这样访问它们
>>> lst[1].split()[1]
>>> '888'
and for the filename.py, you can split it by '"' 对于filename.py,您可以将其拆分为“”
>>> fst = lst[0].split('"')[1]
>>> fst
'/home/path/to/dir/filename.py'
then you can use os.path.basename: 那么你可以使用os.path.basename:
>>> import os.path
>>> os.path.basename(fst)
'filename.py'
Try with this regular expression: 试试这个正则表达式:
File \"[a-zA-Z\/_]*\/([a-zA-Z]+.[a-zA-Z]+)", line ([0-9]+), in (.*)
you can try using this site: https://regex101.com/ 您可以尝试使用此网站: https : //regex101.com/
string = 'File "/home/path/to/dir/filename.py", line 888, in function_name'
search = re.search('File (.*), line (.*), in (.*)', string, re.IGNORECASE)
print search.group(1)
print search.group(2)
print search.group(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.