Python Forum
Help me to using split function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me to using split function
#1
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.))
Reply
#2
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
Reply
#3
Thanks, it works. But how to do it in one line?
Reply
#4
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
Reply
#5
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)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Creating a variable as a function DPaul 23 6,576 Sep-07-2020, 05:20 PM
Last Post: DPaul
  Split function samuelbachorik 1 1,506 Jul-07-2020, 09:14 AM
Last Post: Gribouillis
  How to split a string containing function calls? Metalman488 4 2,845 Oct-27-2018, 06:50 PM
Last Post: Metalman488

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020