0

I'd like to take a user input (like an IP Address) and split the parts into separate variables

for example

255.255.255.0

Now, I would like to split the string by the decimal points and save each part to its own variable. 255 into variable1, 2nd 255 into variable2, 3rd 255 to variable3 and 0 to variable 4 as integers.

How can I do this?

1
  • 1
    You may also want to use regex to ensure that the initial string is in IPv4 address format. Commented Apr 29, 2015 at 16:18

2 Answers 2

5

You could do:

a, b, c, d = input().split(".")

The split() method, by default, splits a string at each space into a list. But, if you add the optional argument, it will split a string by that character/string. You can read more about it at the official documentation

You can also check to make sure the input is in proper IPv4 format.

if re.match("\d+[.]\d+[.]\d+[.]\d+", input()):
    print("IPv4 format")
Sign up to request clarification or add additional context in comments.

Comments

1

might want to add the following to filter for a valid IP:

while(1):
    IP=raw_input("Enter an IP Address:")
    if re.search("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}",IP):
        break
    else:
        print"Invalid Format!"
variable1, variable2, variable3, variable4 = IP.split(".")

Comments

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.