Parsear string ip class c python

2

Hi, I'm trying to separate each of the octets from any ip address but I can not get it.

I have this, it does not work:

j = 0
ip = "a.b.c.d"
for i in ip:
    j = j + 1
    if str(i)==".":
        l = ip[:j]
        print l
    
asked by ellipsys 30.08.2016 в 20:55
source

2 answers

2

Good morning.

Try dividing the string by the character "." :

ip = "192.168.0.123"
result = ip.split(".")
for x in result:
    print x
    
answered by 31.08.2016 в 01:49
1

If you want it as a concept of the use and handling of text strings, you can use this line:

ip = 'a.b.c.d'
clase_c = '.'.join(ip.split('.')[:3])

Use the string '.' as a union of the first three parts ( slices they say in Python) of the string ip divided by the character '.' .

  

lambdas
  I'm sure there is a more pythonic way to do this using lambdas. I hope an expert contributes his opinion.

If you want to work with IP addresses, networks, etc., I recommend the library netaddr .

    
answered by 31.08.2016 в 03:09