I have this very ugly piece of code which runs ethtool and then parses the output (Lilex is just a static class encapsulating subprocess and is not relevant to the question. I'm looking for someone to suggestions to shorten the string manipulation.

        bash_command = "/sbin/ethtool -P " + identifier

        output = Lilex.execute_command(bash_command)

        mac_address = str(output)

        mac_address = mac_address.replace("Permanent address: ", "")
        mac_address = mac_address.replace("\\n", "")
        mac_address = mac_address.replace("'", "")
        mac_address = mac_address[1:].strip()

This is example output that is produced by ethtool -P:

Permanent address: 12:af:37:d0:a9:c8

I'm not sure why I'm replacing single quotes with nothing, but I'm sure I've seen the command output single quotes before, so that part needs to stay.

An alternative suggestion (which is actually not much different):

mac_address = mac_address \
                          .replace("\\n","") \
                          .replace("'","") \
  • 1
    \$\begingroup\$ the string module has lots of fantastic methods for stuff like this. Otherwise you could look into regex. \$\endgroup\$ Commented Aug 14, 2019 at 19:57

1 Answer 1


How about this?

mac_address = mac_address[19:].translate(str.maketrans("", "", "\n':")).strip()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.