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!
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.
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,']
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.
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With