AlexW
AlexW

Reputation: 2587

Pull a string out of a string (split?)

I have a string - a sample would be the below:

g0/1                  192.168.1.1     YES NVRAM  up                    up

I want to pull the IP address out of it but not the last octet. I want to pull 192.168.1. out of it so it can used later.

I think I need to use split, but am not sure on how to achieve this.

output = '    g0/1                  192.168.1.1     YES NVRAM  up                    up'
ouput = ouput.split('192.168.1.',)

Upvotes: 0

Views: 104

Answers (2)

Chuck
Chuck

Reputation: 884

You can use Regular Expressions.

import re

input_string = "g0/1                  192.168.1.1     YES NVRAM  up                    up"
output = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)

EDIT: Changed from match() to search() since match() only looks at the beginning of the string.

Also, assuming you want to do this for more than one string, you can use the findall() function, instead, which will return a list of all the matching groups of your regular expression.

> import re

> input_string = "g0/1                  192.168.1.1     YES NVRAM  up                    up"
> outputs = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)
> print(outputs)
['192.168.1.']

Upvotes: 3

JRodDynamite
JRodDynamite

Reputation: 12623

Simply use split().

>>> output.split()[1].rsplit(".", 1)[0]
'192.168.1'

Upvotes: 6

Related Questions