Daniel Flick
Daniel Flick

Reputation: 93

splitting a variable within mako template

The following works on a Python command line

CELLULAR='1.2.3.4'
OCTETS=CELLULAR_IP.split('.')
FOURTH_OCTET=OCTETS[3]
T101_IP='10.1.1.'+FOURTH_OCTET
T102_IP='10.1.2.'+FOURTH_OCTET
T103_IP='10.1.3.'+FOURTH_OCTET
T104_IP='10.1.4.'+FOURTH_OCTET

But I am having all kinds of trouble doing this in a Mako template. What I am trying to accomplish is to pass the template an IP address in a variable and to grab the last octet of that IP and use it to create 4 other IPs. I thought I could put this in a block like this:

<%
OCTETS=CELLULAR_IP.split('.')
FOURTH_OCTET=OCTETS[3]
T101_IP='10.1.1.'+FOURTH_OCTET
T102_IP='10.1.2.'+FOURTH_OCTET
T103_IP='10.1.3.'+FOURTH_OCTET
T104_IP='10.1.4.'+FOURTH_OCTET
%>

But I get "list index out of range" error. I think this may also be causing some issues with variable scoping as well which I am trying to wrap my head around.

I also tried to define a function to do this but my limited Python abilities are preventing me for succeeding.

def get_octets(ip_string):
   try:
       OCTETS=CELLULAR_IP.split('.')
       return FOURTH_OCTET=OCTETS[3]
   except ValueError:
       return 0

Any ideas on what I should be looking at to accomplish this?

Upvotes: 1

Views: 332

Answers (1)

Daniel Flick
Daniel Flick

Reputation: 93

This works but seems kludgy.

   def get_octets(ip_string):
        try:
           return (ip_string).split('.')[3]
        except:
           # if ip_string won’t contain at least three . catch any exception and return -1
           return -1

Upvotes: 1

Related Questions