1
\$\begingroup\$

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()
dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
asked Aug 14, 2019 at 19:41
\$\endgroup\$
1
  • 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

3
\$\begingroup\$

How about this?

mac_address = mac_address[19:].translate(str.maketrans("", "", "\n':")).strip()
answered Aug 14, 2019 at 19:51
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.