May-18-2019, 06:38 PM
May-18-2019, 11:19 PM
example:
>>> zz = "hgmma = okpiuutt,pddkk,iihg" >>> mm = zz.split('=') >>> yy = mm[1].strip().split(',') >>> result = ','.join(yy[:-1]) >>> result 'okpiuutt,pddkk'You can make this more efficient, and a slice is probably quicker
May-19-2019, 09:40 PM
Thanks, it works. But how to do it in one line?
May-19-2019, 10:19 PM
import re s = "#1 = HouseNumber((7.6,1.2,0.))" extracted = re.search(r'=\s(.+?,[^,]*)', s).group(1) print('Extracted whole =', extracted) name, first_num, second_num = re.search(r'=\s([^(]+)\(\(([^,]*),([^,]*)', s).groups() print('Variables extracted more directly =', name, first_num, second_num)
Output:Extracted whole = HouseNumber((7.6,1.2
Variables extracted more directly = HouseNumber 7.6 1.2
May-19-2019, 11:32 PM
My first idea was also a regex, but regex is not always a good solution.
Don't try to put all your code in one line.
We have enough vertical space, but limited horizontal space.
The second argument is an iterable. In the case of split, it's a list.
Each element of the iterable is applied to the function str.split (), which takes a str as argument.
Usually the map function is lazy, this means you have to iterate over the map object.
Argument unpacking happens on the left side, so the map object is implicit unpacked.
In the second line you see, that I use tuple, to consume the map object. It could be also list, set or something else.
There is only a assignment without unpacking.
Don't try to put all your code in one line.
We have enough vertical space, but limited horizontal space.
def parse_line(line): result, operands = map(str.strip, line.split('=')) operands = tuple(map(str.strip, operands.split(','))) return result, operands parse_line(zz)The map function takes as first argument a function, which accepts one argument.
The second argument is an iterable. In the case of split, it's a list.
Each element of the iterable is applied to the function str.split (), which takes a str as argument.
Usually the map function is lazy, this means you have to iterate over the map object.
Argument unpacking happens on the left side, so the map object is implicit unpacked.
In the second line you see, that I use tuple, to consume the map object. It could be also list, set or something else.
There is only a assignment without unpacking.
Output:('hgmma', ('okpiuutt', 'pddkk', 'iihg'))
Then you can use argument unpackingresult, operands = parse_line(zz)