1

My function scrapes my servers for the command and outputs something along the lines of offset=1.3682 which metrics_emit uses to send to our metrics collector/visualizer, datadog.

What I need to do is strip off the offset= part because metrics_emit only wants the numerical value. What would be the best way of stripping offset= as well as calling strip() on i so that it gets rid of all newlines and trailing/leading whitespaces?

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
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Mara55789
  • 19
  • 1
  • 5

3 Answers3

1

The straightforward way is:

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

For example:

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

Example:

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

Up to you if you need to convert the output.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
0

How to extract the numeric value appeared after 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

Why i prefer regular expression? Because even if the string contains other keywords, regular expression will extract the numeric value which appeared after the offset= expression. For example, check for the following cases with my given example.

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

How to remove leading and trailing whitespace characters?

string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space.

For more flexibility use the following

  • Removes only leading whitespace chars: myString.lstrip()
  • Removes only trailing whitespace chars: myString.rstrip()
  • Removes specific whitespace chars: myString.strip('\n') or myString.lstrip('\n\r') or myString.rstrip('\n\t') and so on.

Reference: see this SO answer.

Community
  • 1
  • 1
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
-1

.strip() for removing whitespace characters.

.replace('offset=', '') for removing that string.

You should be able to chain them too.

moogle
  • 110
  • 9
  • then how OP will get the numeric value part after `offset=`? – Wasi Ahmad Dec 20 '16 at 23:14
  • `string = 'offset=1.3682'` --> `string.replace('offset=', '').strip()` --> `'1.3682'`, which you can use `float()` on to translate it? `.replace()` and `strip()` return the new string... – moogle Dec 20 '16 at 23:20
  • Downvoting my answer and editing part of my answer in so yours gets more exposure. Nice, I like it. – moogle Dec 20 '16 at 23:42
  • i smell something is burning and by the way my answer is far away from yours. i didn't say your answer is wrong but it is not sufficient to get through in every cases. – Wasi Ahmad Dec 21 '16 at 00:30