如何在python中的第一个分隔符实例上分割字符串

时间:2022-09-23 08:22:08

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

我需要使用python分割字符串,但只在字符串中的第一个分隔符实例上。

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:

问题是line,它包含jvm。arg游戏是这样的:

'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!

我希望我的代码分割jvm。在第一个'='时插入键和值变量。re.split默认情况下这样做吗?如果没有建议,我们将不胜感激!

6 个解决方案

#1


25  

This is what str.partition is for:

这就是str.partition的作用:

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

From the docs:

从文档:

str.partition(sep)

str.partition(9月)

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.

在第一次出现sep时分割字符串,并返回一个3元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。如果没有找到分隔符,则返回一个包含字符串本身的3元组,后面跟着两个空字符串。

New in version 2.5.

新的2.5版本中。

#2


10  

From the split documentation

从分割的文档

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

str.split([[,maxsplit]]9月)

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)

返回字符串中的单词列表,使用sep作为分隔符字符串。如果maxsplit被给定,那么在大多数maxsplit分割都完成了(因此,该列表将拥有最多maxsplit+1元素)

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.split('=',1)
['jvm.args', ' -Dappdynamics.com=true, -Dsomeotherparam=false,']

#3


2  

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.

正如某些人在评论中所建议的:您可以解析字符串一次,然后找到“=”,然后从该点对其进行拆分。

#4


1  

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.

我想我将把我的注释转换成(未经测试的)代码,因为它可能比string .partition()更有用。例如,对于需要正则表达式的更复杂的分隔符,可以使用re.match()查找pos。

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:]

#5


0  

I'd skip using regular expressions completely, for a simple string comparison they are not really required.

我将完全跳过使用正则表达式,对于一个简单的字符串比较,它们并不是必需的。

The example code uses an inline method to yield key,value tuples that the dict builtin uses to generate a dictionary (I've not bothered with the file iteration code, your example is correct there):

示例代码使用内联方法生成关键字、值元组,这是dict builtin用来生成字典的值元组(我不关心文件迭代代码,您的示例在这里是正确的):

line="jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, "

# Detect a line that starts with jvm.args
if line.strip().startswith('jvm.args'):
    # Only interested in the args
    _, _, args = line.partition('=')

    # Method that will yield a key, value tuple if item can be converted
    def key_value_iter(args):
        for arg in args:
            try:
                key, value = arg.split('=')
                # Yield tuple removing the -d prefix from the key
                yield key.strip()[2:], value
            except:
                # A bad or empty value, just ignore these
                pass

    # Create a dict based on the yielded key, values
    args = dict(key_value_iter(args.split(',')))

print args will return:

打印参数将返回:

{'appdynamics.com': 'true', 'someotherparam': 'false'}

I assume this is what you are actually after ;)

我猜这就是你真正想要的;)

#6


0  

As suggested in your previous question, ConfigParser is the most straightforward way:

正如您在前一个问题中提到的,ConfigParser是最直接的方法:

import ConfigParser

from io import StringIO

conf = u"""
[options]
foo=bar
jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, 
"""

config = ConfigParser.ConfigParser()
config.readfp(StringIO(conf))
print config.get('options', 'jvm.args')

#1


25  

This is what str.partition is for:

这就是str.partition的作用:

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

From the docs:

从文档:

str.partition(sep)

str.partition(9月)

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.

在第一次出现sep时分割字符串,并返回一个3元组,其中包含分隔符之前的部分、分隔符本身以及分隔符之后的部分。如果没有找到分隔符,则返回一个包含字符串本身的3元组,后面跟着两个空字符串。

New in version 2.5.

新的2.5版本中。

#2


10  

From the split documentation

从分割的文档

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

str.split([[,maxsplit]]9月)

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)

返回字符串中的单词列表,使用sep作为分隔符字符串。如果maxsplit被给定,那么在大多数maxsplit分割都完成了(因此,该列表将拥有最多maxsplit+1元素)

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.split('=',1)
['jvm.args', ' -Dappdynamics.com=true, -Dsomeotherparam=false,']

#3


2  

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.

正如某些人在评论中所建议的:您可以解析字符串一次,然后找到“=”,然后从该点对其进行拆分。

#4


1  

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.

我想我将把我的注释转换成(未经测试的)代码,因为它可能比string .partition()更有用。例如,对于需要正则表达式的更复杂的分隔符,可以使用re.match()查找pos。

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:]

#5


0  

I'd skip using regular expressions completely, for a simple string comparison they are not really required.

我将完全跳过使用正则表达式,对于一个简单的字符串比较,它们并不是必需的。

The example code uses an inline method to yield key,value tuples that the dict builtin uses to generate a dictionary (I've not bothered with the file iteration code, your example is correct there):

示例代码使用内联方法生成关键字、值元组,这是dict builtin用来生成字典的值元组(我不关心文件迭代代码,您的示例在这里是正确的):

line="jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, "

# Detect a line that starts with jvm.args
if line.strip().startswith('jvm.args'):
    # Only interested in the args
    _, _, args = line.partition('=')

    # Method that will yield a key, value tuple if item can be converted
    def key_value_iter(args):
        for arg in args:
            try:
                key, value = arg.split('=')
                # Yield tuple removing the -d prefix from the key
                yield key.strip()[2:], value
            except:
                # A bad or empty value, just ignore these
                pass

    # Create a dict based on the yielded key, values
    args = dict(key_value_iter(args.split(',')))

print args will return:

打印参数将返回:

{'appdynamics.com': 'true', 'someotherparam': 'false'}

I assume this is what you are actually after ;)

我猜这就是你真正想要的;)

#6


0  

As suggested in your previous question, ConfigParser is the most straightforward way:

正如您在前一个问题中提到的,ConfigParser是最直接的方法:

import ConfigParser

from io import StringIO

conf = u"""
[options]
foo=bar
jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, 
"""

config = ConfigParser.ConfigParser()
config.readfp(StringIO(conf))
print config.get('options', 'jvm.args')