简体   繁体   English

如何将字符串分成以“-”开头的部分?

[英]How do I split a string into parts beginning with “--”?

I have a python string like this: 我有一个像这样的python字符串:

str = "--jvm 100 --cpu 200"

How do I get two parts? 如何获得两个部分?

'--jvm 100'
'--cpu 200'

I used str.split('--') and got something that is not optimal: 我使用了str.split('--')并得到了一些并非最佳的东西:

'' 
'jvm 100'
'cpu 200'

I tried regex but can't figure it out. 我试过正则表达式,但无法弄清楚。

Why not add those -- again 为什么不添加这些--再次添加

 input = "--jvm 100 --cpu 200"
 values = ["--%s" % item for item in input.split("--") if item]

Result: ['--jvm 100 ', '--cpu 200'] 结果:['--jvm 100','--cpu 200']

Assuming you're trying to get the values from all the arguments, you should use an argument parsing package to do this. 假设您尝试从所有参数中获取值,则应使用参数解析包来执行此操作。

https://docs.python.org/2/howto/argparse.html https://docs.python.org/2/howto/argparse.html

They're already designed with all the parsing rules so all you'd have to do is focus on getting values out of them. 它们已经设计了所有解析规则,因此您要做的就是专注于从中获取价值。 In many cases, arg parsing tools will let you specify how values should be typed, so numbers will be converted to integers and true/false converted to booleans. 在许多情况下,arg解析工具将允许您指定应如何键入值,因此数字将转换为整数,而true/false将转换为布尔值。

import argparse

# tell our parser what args to expect and what type they are
parser = argparse.ArgumentParser()
parser.add_argument('--jvm', type=int)
parser.add_argument('--cpu', type=int)

raw = '--jvm 100 --cpu 200'
# argparser expects a list of args so split the string on spaces
args = parser.parse_args(raw.split())

# access our parsed args
print args.jvm
print args.cpu

The above is just an example, so you'll need to tune it to meet your needs. 以上只是一个示例,因此您需要对其进行调整以满足您的需求。

使用正则表达式,您可以这样做:

re.findall(r'--.*?(?=\s+--|$)', str)
>>> import re
>>> re.findall(r'--\w+ \d+', str)
['--jvm 100', '--cpu 200']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM