String manipulation in Python

Posted on

Problem

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 
                          .split(":")[1]
                          .replace("\n","") 
                          .replace("'","") 
                          .strip()

Solution

How about this?

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

Leave a Reply

Your email address will not be published. Required fields are marked *