0

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.',)

2 Answers 2

6

Simply use split().

>>> output.split()[1].rsplit(".", 1)[0]
'192.168.1'
Sign up to request clarification or add additional context in comments.

Comments

3

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.']

2 Comments

I would humbly suggest that regular expressions is far too heavy a hammer for this task.
True. I seem to have fallen into the trap of using RegExes even when not necessary.

Your Answer

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.