Python Forum

Full Version: factorise split
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I've general question, not just linked with python (sorry if off topic)

i've a split expression which works:
reason.split(" ")[3].split("(")[2].split(")")[0].split("%")[0]

The expression I want to split is like:
test STATE (64/100)(64%) test1 test2.....

is there any mean to optimize it?

Thanks for help
Alex
With information provided I don't see how it can be 'working'.

>>> reason = 'test STATE (64/100)(64%) test1 test2.....'
>>> reason.split(' ')[3]
'test1'


Next split on this string would be on ( which is not present, so there will be no split and as Python will be looking for item with indice 2 it will raise IndexError.

>>> _.split('(')
['test1']
Thanks !
In fact I want to find value 64 (from 64%) with my split


(Nov-02-2020, 01:41 PM)perfringo Wrote: [ -> ]With information provided I don't see how it can be 'working'.

>>> reason = 'test STATE (64/100)(64%) test1 test2.....'
>>> reason.split(' ')[3]
'test1'


Next split on this string would be on ( which is not present, so there will be no split and as Python will be looking for item with indice 2 it will raise IndexError.

>>> _.split('(')
['test1']
With regex you can make it "simpler" :-D

import re

pattern = re.compile(r"(?P<name>\w+) (?P<state>\w+)\s+\((?P<progress>\d+)\/(?P<total>\d+)\)\((?P<percent>\d+)%\)")
line = "test STATE (64/100)(64%) test1 test2....."

match = pattern.search(line)
if match:
    print(match)
    print(match.group(0)) # All groups
    print(match.group(1)) # Group 1
    print(match.group(2)) # Group 2
    print(match.groupdict())
You can test regex here: https://regex101.com/
[attachment=1038]

Keep in mind, that regex is not for everything good.
I added to the example also names for the groups: [inline=?P<name>][/inline]

If the rest test1 test2..... is also on the same line, then you need to extend the regex.
Just parse line by line.
Thanks for help !