简体   繁体   中英

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? Using a regex?

You can try to use 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

>>> lst[1].split()[1]
>>> '888'

and for the filename.py, you can split it by '"'

>>> fst = lst[0].split('"')[1]
>>> fst
'/home/path/to/dir/filename.py'

then you can use 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/

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM