Sean Klaus
Sean Klaus

Reputation: 189

Split User input into different Variables

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?

Upvotes: 0

Views: 4440

Answers (2)

m0dem
m0dem

Reputation: 1008

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")

Upvotes: 5

bladexeon
bladexeon

Reputation: 706

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(".")

Upvotes: 1

Related Questions