Python Forum
Help me to using split function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help me to using split function (/thread-18454.html)



Help me to using split function - SukhmeetSingh - May-18-2019

I want to split this line from = to second comma in one single line. pls help me anybody?
#1 = HouseNumber((7.6,1.2,0.))


RE: Help me to using split function - Larz60+ - May-18-2019

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


RE: Help me to using split function - SukhmeetSingh - May-19-2019

Thanks, it works. But how to do it in one line?


RE: Help me to using split function - michalmonday - May-19-2019

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



RE: Help me to using split function - DeaD_EyE - May-19-2019

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.

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 unpacking
result, operands = parse_line(zz)