Python for network engineers: strings, f-strings, input, split and slicing
In short: Most data a network script handles starts as text: hostnames, interface names and command output. Python strings have methods to clean, test and change text, f-strings build readable reports, input() asks the user for values, split() breaks a line into fields and slicing picks out exactly the characters you need.
Why text handling comes first
Before structured APIs reach every device, much automation still means reading command output, which arrives as one long piece of text. Even with APIs you build file names, log messages and reports from text. Getting comfortable with Python strings pays off in almost every script. If you are brand new to Python, start with Python basics for network engineers.
Strings and their methods
A string is text in quotes. Single and double quotes work the same; triple quotes hold several lines.
hostname = " Core-SW1 "
clean = hostname.strip() # "Core-SW1"
print(clean.upper()) # CORE-SW1
print(clean.lower()) # core-sw1
print(len(clean)) # 8
print(clean.startswith("Core")) # True
print("SW" in clean) # True
print(clean.replace("SW", "Switch"))
Strings cannot be changed in place; methods return a new string. That is why you write clean = hostname.strip() rather than just calling the method. Useful methods include strip(), lower(), startswith(), endswith(), replace(), find() and join().
f-strings: readable output
An f-string puts an f before the quotes and lets you drop variables and expressions inside braces. It is the clearest way to build messages and file names.
device = "Branch-R1"
up, total = 22, 24
print(f"{device}: {up} of {total} interfaces up")
print(f"{device}: {up / total:.1%} available")
filename = f"{device.lower()}-backup.cfg"
The part after a colon is a format specification: .1% shows a percentage with one decimal place, >10 right-aligns in ten characters, which helps when printing tidy tables.
Asking for input
input() shows a prompt and returns what the user typed, always as a string. Convert it when you need a number, and never use it for passwords: the getpass module hides what is typed.
vlan = int(input("VLAN number: "))
name = input("VLAN name: ").strip().upper()
from getpass import getpass
secret = getpass("Device password: ")
Validate what users type. A script that pushes VLAN configuration should reject 0, 4095 or text before it touches a switch.
Python also offers join(), the opposite of split(): ",".join(["10", "20", "30"]) produces 10,20,30, which is exactly the format a trunk's allowed VLAN list expects. Building configuration lines from lists like this is one of the most common jobs in small automation scripts, and it avoids the typing mistakes that creep in when long lists are copied by hand.
split() and slicing: picking values out
split() with no argument breaks a string on any run of spaces; give it a character to split on something else. splitlines() breaks text into lines. Indexes start at 0, and negative indexes count from the end.
line = "Gi1/0/5 unassigned YES unset up up"
fields = line.split()
print(fields[0]) # Gi1/0/5
print(fields[-1]) # up (protocol status)
ip = "192.168.20.15"
octets = ip.split(".") # ["192", "168", "20", "15"]
mac = "0011.2233.4455"
print(mac[:4]) # 0011 (first four characters)
print(mac[-4:]) # 4455 (last four)
print(ip[::-1]) # reversed string
A slice is written [start:stop:step]; the stop position is not included. Slices never raise an error if they run past the end, which makes them safer than single indexes. For complex output, move on to regular expressions, or better, ask the device for structured data.
Tip: the most common beginner mistakes with text are mixing types and forgetting about case and spaces. "VLAN " + 10 fails because you cannot add a number to a string; use an f-string or str(10). Device output often has trailing spaces or mixed case, so strip() and lower() values before you compare them.
Real-world example: a quick port report
A support technician at a fictional estate agency group was asked which switch ports were down in each office. He saved the output of show ip interface brief from each switch to a text file, then wrote a twelve-line script. It read each file with splitlines(), skipped the header line, used split() to get the interface name and the last field, and kept the lines where the status was "down". An f-string printed one tidy line per port, such as "Office-3 Gi1/0/14 down". The report took two minutes instead of an afternoon, and the same script now runs every Monday.
Practice
What does " Gi1/0/1 ".strip() return, and why must you assign it?
How do you get the third octet of ip = "10.1.20.5"?
What does mac[-4:] return for "0011.2233.4455"?
Key takeaways
- Strings hold text; methods return new strings rather than changing the old one.
- f-strings build clear messages and reports, with format specifiers.
- input() always returns a string; use getpass for passwords and validate input.
- split() and splitlines() turn output into lists of fields and lines.
- Indexes start at 0; slices use [start:stop:step] and exclude the stop.
Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.