Best way to use split and strip

5.7k views Asked by At

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
3

There are 3 answers

4
moogle On

.strip() for removing whitespace characters.

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

You should be able to chain them too.

0
Wasi Ahmad On

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.

0
Chris Johnson On

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.