Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split a string on the first instance of delimiter in python

I need to split a string using python but only on the first instance of the delimiter in the string.

My code:

for line in conf.readlines():
    if re.search('jvm.args',line):
        key,value= split('=',line)
        default_args=val

The problem is line, which contains jvm.args looks like this:

'jvm.args = -Dappdynamics.com=true, -Dsomeotherparam=false,'

I want my code to split jvm.args into key and value variables incidently upon the first '='. Does re.split do this by default? If not a suggestion would be appreciated!

like image 283
user1371011 Avatar asked Jun 13 '12 06:06

user1371011


4 Answers

This is what str.partition is for:

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.partition('=')
('jvm.args', '=', ' -Dappdynamics.com=true, -Dsomeotherparam=false,')

From the docs:

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

New in version 2.5.

like image 155
Kenan Banks Avatar answered Oct 16 '22 13:10

Kenan Banks


From the split documentation

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements)

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.split('=',1)
['jvm.args', ' -Dappdynamics.com=true, -Dsomeotherparam=false,']
like image 38
Burhan Khalid Avatar answered Oct 16 '22 14:10

Burhan Khalid


I think this should work :

lineSplit = line.split("=")
key = lineSplit[0]
value = "=".join(lineSplit[1:])

As someone suggested in comments: you can just parse through string once and locate "=" , followed by splitting it from that point.

like image 2
damned Avatar answered Oct 16 '22 13:10

damned


I guess I'll turn my comment into (untested) code because it might be useful at a lower level than str.partition(). For example, for a more complicated delimiter requiring a regular expression, you could use re.match() to find pos. But Triptych's suggestion got my vote.

Here you go:

pos = -1
for i, ch in enumerate(line):
    if ch == '=':
        pos = i
        break
if pos < 0: raise myException()

key = line[:pos]
value = line[pos+1:]
like image 1
Codie CodeMonkey Avatar answered Oct 16 '22 13:10

Codie CodeMonkey