使用拆分和剥离的最佳方法

时间:2016-12-20 23:09:55

标签: python split strip

我的功能在我的服务器上搜索命令,并输出offset=1.3682 metrics_emit用来发送到我们的metrics collector / visualizer,datadog的offset=行。

我需要做的是剥离metrics_emit部分因为offset=只想要数值。剥离strip()以及在i上调用def check(self): output = sh.ntpq("-nc rv") out_list = output.split(",") for i in out_list: if "offset" in i: self.metrics_emit('ntp.offset', i) break 以便删除所有换行符和尾随/前导空格的最佳方法是什么?

{{1}}

3 个答案:

答案 0 :(得分:1)

直截了当的方式是:

i.strip().split('offset=')[1]

例如:

def scrape(line):
    return line.strip().split('offset=')[1]

示例:

>>> scrape('offset=1.3682')
'1.3682'

如果您需要转换输出,请由您决定。

答案 1 :(得分:0)

  

如何提取offset=之后出现的数值?

import re
regex = re.compile('offset=([\d+\.\d+]+)')
string = 'offset=1.3682'

match = re.search(regex, string)
if match:
    print(match.group(0)) # prints - offset=1.3682
    print(match.group(1)) # prints - 1.3682

为什么我更喜欢正则表达式?因为即使字符串包含其他关键字,正则表达式也会提取offset=表达式后面出现的数值。例如,使用我给出的示例检查以下情况。

string = 'welcome to offset=1.3682 Stackoverflow'
string = 'offset=abcd'
  

如何删除前导和尾随空格字符?

string.strip()

将删除所有前导和尾随空格字符,例如\ n,\ r \ n,\ t \ t,\ t \ t \ t,空格。

为了更加灵活,请使用以下

  • 仅移除前导空白字符:myString.lstrip()
  • 仅移除尾随空白字符:myString.rstrip()
  • 移除特定空白字符:myString.strip('\n')myString.lstrip('\n\r')myString.rstrip('\n\t'),依此类推。

参考:请参阅此SO answer

答案 2 :(得分:-1)

{ "$schema": "http://json-schema.org/draft-04/schema", "id": "resource:/schemas/results_schema#", "type": "array", "items": { "type": "object", "required": ["type", "name"], "properties": { "name": { "type": "string" }, "dateOfBirth": { "type": "string" } } } } 用于删除空白字符。

.strip()用于删除该字符串。

您也应该能够将它们链接起来。

相关问题