Skip to content
Home » Blog » Python for Network Engineers Blog 12: Python Type Conversion

Python for Network Engineers Blog 12: Python Type Conversion

Main blog image summarising Python type conversion for network engineers. Shows code converting interface speed values, a network device table before and after type conversion, and a network diagram background

Python Type Conversion – Stop Converting Temperatures and Start Converting Network Data

Right, so you’ve got booleans working haven’t you, got floats sorted, integers done, strings working properly. Now we’re onto python type conversion.

Python for Network Engineers Blog 11: Python Booleans

Now here’s where most Python courses completely lose the plot again. They’ll have you converting temperatures from Celsius to Fahrenheit or working out currency conversions or figuring out how to turn someone’s age from a string into a number for birthday calculations. I’m sitting there thinking, that’s lovely mate but I’ve got SNMP data coming in as strings that needs to be integers and CSV files with mixed data types to parse. How’s Dave’s birthday going to help me convert interface utilisation from “67.8” to an actual number I can do calculations with then?

Look, I made this exact mistake when I started. About eighteen months back, kept running into issues where my monitoring scripts would break because everything was coming in as the wrong data type. Tried following some online Python courses to understand type conversion. First one I tried, they’re teaching me to convert shoe sizes and calculate someone’s retirement age. I’m thinking how’s this going to help me parse router configuration files then?

Few months later, had this massive data parsing project. Network inventory system exporting everything as text, SNMP returning strings for numeric values, user input needing validation before configuration changes. Everything was the wrong type for what I needed to do with it. Thought there’s got to be a better way than constantly debugging type errors.

Found someone who explained it properly using actual network data examples. Made much more sense straight away. Instead of learning about converting Dave’s shoe size, I’m learning about converting SNMP interface counters. Instead of working out retirement calculations, I’m converting user input to proper VLAN IDs.

So let’s do python type conversion properly using network stuff that matters.

What Type Conversion Actually Does

Right so type conversion in Python, it’s just changing data from one type to another isn’t it. String to integer, integer to string, float to boolean, whatever you need.

# Converting network data types
vlan_string = "10"          # String from user input
vlan_number = int(vlan_string)   # Convert to integer

bandwidth_text = "1000.5"   # String from CSV file  
bandwidth_float = float(bandwidth_text)  # Convert to float

device_count = 24           # Integer from calculation
device_string = str(device_count)  # Convert to string for display

See? Actual networking data conversions. Not how much Dave weighs in different units.

Now here’s something quite clever about python type conversion that I didn’t appreciate when I started. Python’s really good at figuring out what you mean, but sometimes you need to be explicit about the conversion. Especially when you’re dealing with network data that comes from different sources.

Actually had this come up just last week. Working with some SNMP polling that was returning interface speeds as strings, but I needed to do mathematical comparisons to check for 10Gig interfaces. Python couldn’t automatically compare “10000000000” with 1000000000 because one’s a string and one’s an integer. Had to explicitly convert the SNMP data before the comparison would work properly.

Why This Matters for Network Engineers

Look, networking’s absolutely stuffed with data type mismatches, isn’t it? SNMP returns strings, CSV files mix text and numbers, user input always comes as strings, configuration templates need specific data types. Everything’s coming in as the wrong type for what you need to do with it.

Understanding python type conversion properly means you can work with all this mixed data without constantly hitting type errors. Makes your data processing scripts much more reliable.

# Common network data type issues
snmp_bandwidth = "1000000000"    # SNMP returns string
csv_vlan_id = "10"              # CSV data is text
user_port_count = input("How many ports? ")  # Input is always string
config_speed = 1000             # Your script uses integer

These need conversion before you can use them together in calculations or comparisons. Can’t compare a string “1000000000” with an integer 1000 can you? Python doesn’t know if you want to compare them as numbers or as text.

But here’s where people get confused. When do you need explicit conversion versus when does Python handle it automatically?

When Python Converts Automatically vs When You Need to Convert

This catches people out constantly. Sometimes Python converts data types automatically, sometimes you have to do it explicitly.

Python automatically converts in mathematical operations between compatible types:

# Automatic conversion that works
port_count = 24        # Integer
utilisation = 67.5     # Float
result = port_count * utilisation  # Python converts int to float automatically

But Python won’t automatically convert between incompatible types:

# This will fail
vlan_id = "10"         # String
port_count = 24        # Integer
total = vlan_id + port_count  # Error - can't add string and int

# Need explicit conversion
vlan_id = "10"
port_count = 24
total = int(vlan_id) + port_count  # Now it works
Code editor screenshot showing python type conversion errors with red error messages, then the corrected code working properly

Got caught out by this early on actually. Had a script that was reading VLAN IDs from a CSV file, trying to add them to a counter for reporting. Kept getting type errors because the CSV data was strings but my counter was an integer. Spent ages debugging before I realised I needed to convert the CSV strings to integers first. Felt like a right pillock.

The key thing is understanding what data types you’re working with and when you need to explicitly convert between them.

Converting Strings to Numbers

This is probably the most common conversion you’ll do with network data. Everything comes in as strings – user input, CSV files, SNMP responses, API returns. But you need numbers for calculations.

# String to integer conversion
vlan_string = "20"
vlan_number = int(vlan_string)  # Converts "20" to 20

# String to float conversion  
bandwidth_string = "1000.5"
bandwidth_number = float(bandwidth_string)  # Converts "1000.5" to 1000.5

# Multiple conversions from network data
interface_data = {
    "speed": "1000000000",      # String from SNMP
    "utilisation": "67.8",      # String from monitoring
    "mtu": "1500"               # String from config
}

# Convert to proper types
processed_data = {
    "speed": int(interface_data["speed"]),           # Now integer
    "utilisation": float(interface_data["utilisation"]), # Now float  
    "mtu": int(interface_data["mtu"])                # Now integer
}

This comes up constantly when you’re parsing network data. SNMP, CSV exports, user input, API responses – they all tend to give you strings even when the data represents numbers.

Had this exact problem last month actually. Pulling interface statistics from multiple devices, some returning integers, some returning strings. Without consistent type conversion, half my calculations were wrong. Once I normalised everything to the right data types, the math worked perfectly.

But here’s where it gets tricky. What happens when the string can’t be converted?

Handling Conversion Errors

Network data is messy. Users type rubbish, SNMP timeouts return error messages, CSV files have missing values. Your conversion code needs to handle this gracefully.

# This will crash if the string isn't a valid number
user_input = "not_a_number" 
vlan_id = int(user_input)  # ValueError: invalid literal for int()

# Better approach with error handling
def safe_int_conversion(value, default=0):
    try:
        return int(value)
    except ValueError:
        print(f"Cannot convert '{value}' to integer, using default {default}")
        return default

# Usage with unreliable network data
user_vlan = safe_int_conversion(input("Enter VLAN ID: "), default=1)
snmp_speed = safe_int_conversion(snmp_response.get("interface_speed"), default=0)

This kind of error handling prevents your scripts from crashing when they encounter bad data, which happens more often than you’d think in network automation.

Not handling conversion errors properly bit me badly once. Had a monitoring script that was processing interface statistics, but some devices returned “N/A” for unavailable interfaces. Script crashed every time it hit one of those instead of skipping the bad data. Proper embarrassing when the monitoring went down during a network issue.

Always use try/except when converting strings to numbers, especially with user input or data from external systems.

Converting Numbers to Strings

Sometimes you need to go the other way – convert numbers to strings for display, logging, or building configuration commands.

# Number to string conversion
vlan_id = 10
vlan_string = str(vlan_id)  # Converts 10 to "10"

# For building configuration commands
interface_number = 1
config_command = f"interface GigabitEthernet0/{str(interface_number)}"
# Results in "interface GigabitEthernet0/1"

# For formatted output
bandwidth_mbps = 1000.5
report_line = f"Bandwidth: {str(bandwidth_mbps)} Mbps"

This comes up loads when you’re generating configuration files or building command strings. The configuration syntax expects text, but your script is working with numbers.

Actually, let me tell you about a time this caught me out. Working on some automated VLAN deployment, building configuration commands from a list of VLAN IDs. Kept getting errors because I was trying to concatenate integers directly into strings. Took me ages to work out I needed to convert the VLAN IDs to strings first. Don’t be like me – remember that string operations need strings.

But here’s a clever bit. You often don’t need explicit str() conversion when using f-strings:

# These both work the same way
vlan_id = 10
command1 = f"vlan {str(vlan_id)}"  # Explicit conversion
command2 = f"vlan {vlan_id}"       # Automatic conversion

# Both result in "vlan 10"

F-strings automatically convert numbers to strings, which makes building configuration commands much cleaner.

Converting Between Different Number Types

Sometimes you need to convert between integers and floats for different types of network calculations.

# Float to integer (removes decimal places)
utilisation_float = 67.8
utilisation_int = int(utilisation_float)  # Becomes 67 (not rounded!)

# Integer to float (adds decimal precision)
port_count = 24
port_percentage = float(port_count)  # Becomes 24.0

# Be careful - int() truncates, doesn't round
bandwidth_float = 999.9
bandwidth_int = int(bandwidth_float)  # Becomes 999, not 1000!

# If you want rounding, use round() first
bandwidth_rounded = int(round(bandwidth_float))  # Becomes 1000

This distinction between truncation and rounding catches people out constantly. int() just chops off the decimal part, it doesn’t do proper rounding.

Had this bite me on a capacity planning script. Converting percentage utilisation to whole numbers for reporting, but int() was truncating instead of rounding. So 89.9% utilisation was showing as 89% instead of 90%, which made the reports misleading. Had to add proper rounding to get accurate results.

Screenshot of a code editor with side-by-side panels: on the left, Python code using networking examples shows python type conversion errors with red error messages; on the right, the corrected code runs successfully, demonstrating proper type conversion in a network automation context

Converting Booleans

Python booleans convert to numbers and strings in predictable ways, which is useful for network status reporting.

# Boolean to integer
interface_up = True
status_code = int(interface_up)  # True becomes 1, False becomes 0

# Boolean to string
backup_successful = False
status_text = str(backup_successful)  # Becomes "False"

# Numbers and strings to boolean
online_status = bool(1)          # Any non-zero number becomes True
device_name = bool("SW1-ACCESS") # Any non-empty string becomes True
empty_config = bool("")          # Empty string becomes False
zero_errors = bool(0)           # Zero becomes False

This is brilliant for converting between different monitoring systems that represent status differently. Some use 1/0, some use True/False, some use up/down text.

# Standardise different status formats
def normalise_status(status):
    if isinstance(status, bool):
        return status
    elif isinstance(status, int):
        return bool(status)  # 0 = False, anything else = True
    elif isinstance(status, str):
        return status.lower() in ["true", "up", "active", "enabled", "1"]
    else:
        return False  # Default to False for unknown types

# Usage with mixed data sources
snmp_status = normalise_status(1)           # Returns True
api_status = normalise_status("up")         # Returns True
csv_status = normalise_status("False")      # Returns False

Actually used something like this on a project where I was pulling device status from three different systems. Each one used different formats for “up” and “down”. The normalisation function let me work with consistent boolean values regardless of the source.

Real Network Examples

Let me show you actual scenarios where type conversion matters.

Processing CSV network inventory:

# CSV data comes in as strings
csv_data = [
    {"hostname": "SW1-ACCESS", "port_count": "24", "uptime": "45.5"},
    {"hostname": "R1-EDGE-RTR", "port_count": "4", "uptime": "123.2"},
    {"hostname": "SW2-ACCESS", "port_count": "48", "uptime": "67.8"}
]

# Convert to proper types for calculations
processed_inventory = []
for device in csv_data:
    processed_device = {
        "hostname": device["hostname"],                    # Keep as string
        "port_count": int(device["port_count"]),          # Convert to int
        "uptime": float(device["uptime"])                 # Convert to float
    }
    processed_inventory.append(processed_device)

# Now you can do proper calculations
total_ports = sum(device["port_count"] for device in processed_inventory)
average_uptime = sum(device["uptime"] for device in processed_inventory) / len(processed_inventory)

print(f"Total network ports: {total_ports}")
print(f"Average uptime: {average_uptime:.1f} days")

Much more reliable than trying to do math with string data.

SNMP data processing:

# SNMP returns interface data as strings
snmp_interfaces = {
    "Gi0/1": {"speed": "1000000000", "in_octets": "234567890", "errors": "0"},
    "Gi0/2": {"speed": "1000000000", "in_octets": "567890123", "errors": "5"},
    "Te0/1": {"speed": "10000000000", "in_octets": "1234567890", "errors": "0"}
}

# Convert for bandwidth calculations
for interface, data in snmp_interfaces.items():
    speed_bps = int(data["speed"])
    octets = int(data["in_octets"])
    error_count = int(data["errors"])
    
    # Calculate utilisation percentage
    utilisation = (octets * 8 / speed_bps) * 100  # Convert octets to bits
    
    print(f"{interface}: {utilisation:.1f}% utilisation, {error_count} errors")

Without proper type conversion, you can’t do the bandwidth calculations because you’d be trying to divide strings.

User input validation:

def get_valid_vlan_id():
    while True:
        user_input = input("Enter VLAN ID (1-4094): ")
        try:
            vlan_id = int(user_input)
            if 1 <= vlan_id <= 4094:
                return vlan_id
            else:
                print("VLAN ID must be between 1 and 4094")
        except ValueError:
            print("Please enter a valid number")

# Usage in configuration scripts
new_vlan = get_valid_vlan_id()
config_command = f"vlan {new_vlan}"
print(f"Creating: {config_command}")

This kind of input validation with type conversion prevents configuration errors before they happen.

Advanced Type Conversion Scenarios

Sometimes you need more sophisticated conversion handling for complex network data.

Converting mixed data types from APIs:

# API response with mixed types
api_response = {
    "device_info": {
        "hostname": "SW1-ACCESS",
        "mgmt_ip": "192.168.100.11", 
        "port_count": "24",           # String in API
        "cpu_usage": 23.7,            # Already float
        "memory_usage": "67",         # String in API
        "uptime_seconds": 3888000,    # Already int
        "config_changed": "true"      # String boolean
    }
}

def convert_device_data(device_data):
    converted = {}
    
    # String fields stay as strings
    converted["hostname"] = str(device_data["hostname"])
    converted["mgmt_ip"] = str(device_data["mgmt_ip"])
    
    # Convert numeric fields
    converted["port_count"] = int(device_data["port_count"])
    converted["cpu_usage"] = float(device_data["cpu_usage"]) 
    converted["memory_usage"] = int(device_data["memory_usage"])
    converted["uptime_seconds"] = int(device_data["uptime_seconds"])
    
    # Convert boolean field
    config_changed = str(device_data["config_changed"]).lower()
    converted["config_changed"] = config_changed in ["true", "1", "yes"]
    
    # Calculate derived values
    converted["uptime_days"] = converted["uptime_seconds"] / 86400
    
    return converted

# Process the API data
device_info = convert_device_data(api_response["device_info"])
print(f"Device {device_info['hostname']} has been up for {device_info['uptime_days']:.1f} days")

This kind of comprehensive data conversion is essential when you’re integrating multiple systems with different data formats.

Handling network configuration templates:

# Template variables need specific types
template_vars = {
    "hostname": "SW1-ACCESS",        # String
    "mgmt_ip": "192.168.100.11",    # String (IP addresses stay as strings)
    "vlan_id": 10,                  # Integer
    "vlan_name": "Sales",           # String
    "port_count": 24                # Integer
}

def validate_template_vars(variables):
    validated = {}
    
    # Ensure hostname is string
    validated["hostname"] = str(variables["hostname"])
    
    # Ensure mgmt_ip is string (IP addresses don't need numeric conversion)
    validated["mgmt_ip"] = str(variables["mgmt_ip"])
    
    # Ensure VLAN ID is valid integer
    vlan_id = int(variables["vlan_id"])
    if not 1 <= vlan_id <= 4094:
        raise ValueError(f"Invalid VLAN ID: {vlan_id}")
    validated["vlan_id"] = vlan_id
    
    # Ensure VLAN name is string
    validated["vlan_name"] = str(variables["vlan_name"])
    
    # Ensure port count is positive integer
    port_count = int(variables["port_count"])
    if port_count <= 0:
        raise ValueError(f"Invalid port count: {port_count}")
    validated["port_count"] = port_count
    
    return validated

# Use in configuration generation
try:
    validated_vars = validate_template_vars(template_vars)
    config = f"""
vlan {validated_vars['vlan_id']}
 name {validated_vars['vlan_name']}
!
interface range gi0/1-{validated_vars['port_count']}
 switchport access vlan {validated_vars['vlan_id']}
"""
    print("Configuration generated successfully")
except ValueError as e:
    print(f"Template validation failed: {e}")

This ensures your configuration templates get the right data types and prevents syntax errors in the generated configurations.

Type Conversion for Data Export

When you’re exporting network data for reporting or analysis, you often need to convert to specific formats.

# Preparing network data for CSV export
network_stats = [
    {"device": "SW1-ACCESS", "cpu": 23.7, "memory": 67, "interfaces": 24, "online": True},
    {"device": "R1-EDGE-RTR", "cpu": 45.2, "memory": 34, "interfaces": 4, "online": False},
    {"device": "SW2-ACCESS", "cpu": 12.1, "memory": 89, "interfaces": 48, "online": True}
]

# Convert for CSV format (everything needs to be strings)
csv_rows = []
for device_stats in network_stats:
    csv_row = [
        str(device_stats["device"]),        # Already string, but ensure consistency
        f"{device_stats['cpu']:.1f}",       # Format float to 1 decimal place
        str(device_stats["memory"]),        # Convert int to string
        str(device_stats["interfaces"]),    # Convert int to string
        "UP" if device_stats["online"] else "DOWN"  # Convert boolean to meaningful text
    ]
    csv_rows.append(csv_row)

# Write to CSV
import csv
with open("network_stats.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Device", "CPU %", "Memory %", "Interfaces", "Status"])
    writer.writerows(csv_rows)

The type conversions ensure your exported data is properly formatted and readable.

image of a  CSV file showing properly formatted network data with correct data types

PCEP Requirements for Type Conversion

The PCEP exam covers specific aspects of python type conversion that you need to understand properly.

Built-in conversion functions:

# Integer conversion
int("123")      # String to int: 123
int(45.7)       # Float to int: 45 (truncated, not rounded)
int(True)       # Boolean to int: 1
int(False)      # Boolean to int: 0

# Float conversion  
float("123.45") # String to float: 123.45
float(123)      # Int to float: 123.0
float(True)     # Boolean to float: 1.0

# String conversion
str(123)        # Int to string: "123"
str(45.7)       # Float to string: "45.7"
str(True)       # Boolean to string: "True"

# Boolean conversion
bool(1)         # Non-zero int to bool: True
bool(0)         # Zero to bool: False
bool("text")    # Non-empty string to bool: True
bool("")        # Empty string to bool: False

Type conversion exceptions:

# These will raise ValueError
int("not_a_number")    # Cannot convert invalid string
float("invalid")       # Cannot convert invalid string
int("123.45")         # Cannot convert float string to int directly

# Need to handle exceptions
try:
    result = int("abc")
except ValueError:
    print("Invalid conversion")

Implicit vs explicit conversion:

# Implicit conversion (automatic)
result = 5 + 3.2        # int + float = float (5.0 + 3.2 = 8.2)
output = "VLAN " + str(10)  # Must explicitly convert int to string

# Explicit conversion (manual)
user_input = "25"
vlan_id = int(user_input)   # Must explicitly convert string to int

These are the specific PCEP requirements, but understanding them through networking examples makes much more sense than abstract conversion exercises.

Why This All Actually Matters

Understanding python type conversion properly is fundamental to any network data processing you’ll do. CSV parsing, SNMP processing, user input validation, API integration – they all depend on handling data type conversions correctly.

Get type conversion wrong and your scripts will crash with type errors. Data calculations will be wrong, user input will cause failures, monitoring systems will break when they encounter unexpected data. Get it right and you can reliably process data from any source.

The key thing is using python type conversion for actual network data problems. SNMP counters, CSV inventories, user configuration input, API responses. Not abstract mathematical conversions that don’t help anyone.

When you’re working with network automation, data analysis, monitoring systems, all the data processing becomes much easier once you’re comfortable with type conversion and error handling.

Actually, let me tell you something that really drove this home for me. Had a colleague who’d been struggling with a network inventory script for weeks. It kept crashing whenever it hit certain devices. Turns out the script was trying to do mathematical calculations on string data from the CSV export. Some devices had “N/A” in numeric fields, others had leading spaces that prevented conversion. Spent an afternoon showing him proper type conversion with error handling, and suddenly his script became bulletproof. It could handle any data the CSV threw at it and still produce useful results.

That’s the difference proper understanding makes. It’s not just about passing PCEP or looking clever. It’s about writing scripts that can reliably process real-world network data, no matter how messy it gets.

That’s python type conversion sorted properly. You understand what it is, how it works with network data, common mistakes to avoid, and practical applications for real network engineering tasks. Much more useful than learning about theoretical temperature conversions that have nothing to do with your actual job.


External Link: Python Built-in Functions Documentation – official Python documentation for type conversion functions like int(), float(), str(), and bool()

1 thought on “Python for Network Engineers Blog 12: Python Type Conversion”

  1. Pingback: Python for Network Engineers Blog 13: Scientific Notation - RichardKilleen

Leave a Reply

Your email address will not be published. Required fields are marked *