en803
en803

Reputation: 35

How to extract characters from strings

I run the code:

from subprocess import Popen, PIPE

p1 = Popen(['ip', 'addr'], stdout=PIPE)
p2 = Popen(['grep', 'enp'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output=p2.communicate()[0]
print(output)

and I get the output:

b'7: enp0s20f0u1c4i2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000\n    inet 172.20.10.2/28 brd 172.20.10.15 scope global dynamic enp0s20f0u1c4i2\n'

How to extract the characters enp0s20f0u1c4i2 from the string of this output?

Upvotes: 0

Views: 54

Answers (1)

excalibur1491
excalibur1491

Reputation: 1221

If you are sure that the string output always has that same format, you could use the split function to split in :, take the first element and then clean the string to remove the spaces and \n. Similarly you could split by space and get the last element of the split (it seems the string you are looking for appears twice?)

So output.split(':')[1].strip() or output.split(' ')[-1].strip().

Upvotes: 1

Related Questions