Why Strings Are Central to Network Automation
When you run show ip interface brief, what comes back is a string. Same for show bgp summary, show version, show running-config. The entire output of every CLI command is a string. If you can't work with strings, you can't parse anything.
Most network automation scripts spend most of their time doing two things: running commands and processing the output. The second part is all string work.
String Basics
A string is any text in quotes. Single quotes and double quotes both work in Python. Triple quotes let you span multiple lines, which is useful for multi-line CLI output stored in a variable.
hostname = 'router-core-1'
interface = "GigabitEthernet0/0" multiline = """
Interface IP-Address OK? Method Status
GigabitEthernet0/0 10.0.0.1 YES NVRAM up
"""
Building Strings: Concatenation and f-strings
You can join strings with +. But for anything beyond trivial cases, f-strings are cleaner. They let you embed variables directly inside the string using curly braces.
hostname = "router1"
ip = "10.0.0.1" # Concatenation (old way)
print("Connecting to " + hostname + " at " + ip) # f-string (better)
print(f"Connecting to {hostname} at {ip}")
f-strings work with any Python expression inside the braces: f"Hosts: {len(device_list)}", f"Up: {status.upper()}".
The Methods You Will Use Every Day
Python strings have dozens of built-in methods. These are the ones that show up in network scripts constantly:
line = " GigabitEthernet0/0 10.0.0.1 up up " line.strip() # remove leading/trailing whitespace
line.lower() # "gigabitethernet0/0 10.0.0.1 up up"
line.upper() # "GIGABITETHERNET0/0 10.0.0.1 UP UP"
line.split() # ['GigabitEthernet0/0', '10.0.0.1', 'up', 'up']
line.startswith("G") # True
line.endswith("up") # True (after strip)
line.replace("up", "UP") # substitution
line.find("0.0") # returns index of first match, or -1
.strip() is almost always the first method applied to any line from CLI output. Device output often has trailing spaces or inconsistent indentation.
Indexing and Slicing
Strings are sequences in Python. You access individual characters or ranges using square bracket notation.
s = "GigabitEthernet0/0" s[0] # "G" , first character
s[-1] # "0" , last character
s[0:7] # "Gigabi" , characters 0 through 6
s[7:] # "tEthernet0/0" , from index 7 to end
s[:7] # "Gigabi" , from start to index 6
s[::2] # every other character
Negative indices count from the end: s[-3:] gives the last 3 characters. This is useful for extracting port numbers or interface suffixes.
Iterating Over Lines
Show command output is usually multiple lines. The most common pattern is .splitlines() to break it into a list, then loop over each line.
output = conn.send_command("show ip interface brief") for line in output.splitlines(): if "up" in line.lower(): print(line)
The in operator checks if a substring exists: "up" in line returns True if "up" appears anywhere in line. It's case-sensitive, so pair it with .lower() for reliable matching.
A Real Parsing Example
Parse show ip interface brief and return a list of dicts, one per interface:
def parse_ip_brief(output): interfaces = [] for line in output.splitlines(): line = line.strip() if not line or line.startswith("Interface"): continue # skip header and blank lines parts = line.split() if len(parts) >= 6: interfaces.append({ "interface": parts[0], "ip": parts[1], "status": parts[4], "protocol": parts[5], }) return interfaces # Usage:
output = conn.send_command("show ip interface brief")
for intf in parse_ip_brief(output): if intf["status"] == "up": print(f"{intf['interface']} is up ({intf['ip']})")
This is the pattern you'll repeat for most show commands: split into lines, skip headers, split each line on whitespace, extract the fields you care about by index.
When String Methods Are Not Enough
Some CLI output doesn't have clean whitespace-separated columns. Descriptions with spaces, inconsistent formatting, or optional fields will break naive split-by-whitespace parsing. For those cases, use TextFSM templates (via Netmiko's use_textfsm=True flag) or regular expressions.
But for the majority of common show commands, the methods above are all you need.
Watch the video
This topic has a full video on YouTube.
Next in this series
Python split, Index, and Slice: The Three Tools That Parse Any CLI Output →
Comments (0)
Please sign in to comment.