Why Python, the REPL, and Strings

Set up a clean Python environment, get comfortable in the interactive interpreter, and use string operations to pull real facts out of real device output — the single most common task in network automation.

In this lesson you will:
  • Explain why Python is the default language of network automation
  • Create and activate a virtual environment you'll reuse all course
  • Use the REPL to experiment faster than you can write scripts
  • Parse device output with .split(), .join(), .strip(), and membership checks
  • Format clean tabular output with f-strings

Why Python? Because the CLI doesn’t scale

You can configure one switch by hand. You can probably configure ten and stay sane. But the day the work order says “validate NTP, AAA, and the management ACL on every access switch in the district”, the CLI stops being a tool and starts being a liability. Box-by-box work doesn’t just take longer — it drifts. Two engineers typing the “same” config produce three versions of it.

Python is how network engineers get out of that trap, and it has quietly become the lingua franca of the discipline: the major automation libraries (Netmiko, NAPALM, Nornir), every vendor SDK, and every NetDevOps pipeline you will ever touch all speak it. The skills stack like this:

  1. Read device output into a program instead of your eyeballs
  2. Decide with code (compliant or not? matches intent or not?)
  3. Act at scale — push config, run checks, open tickets

This course teaches step 1 and the Python fundamentals under it — entirely on network data. You will not print "Hello, world". You will extract a serial number from show version, because that is the actual job.

Set up your environment once, properly

You need Python 3.12 or newer (python.org/downloads) and a terminal. Everything in this course works on macOS, Linux, or Windows (native or WSL2).

Professional Python work happens inside a virtual environment — a private, disposable copy of Python per project, so the libraries you install never collide with your system or with other projects:

# Make a home for your course work
mkdir -p ~/pyfoundations && cd ~/pyfoundations

# Create the virtual environment (one time)
python3 -m venv .venv

# Activate it (every session)
source .venv/bin/activate        # macOS / Linux
# .venv\Scripts\activate         # Windows PowerShell

# Your prompt now shows (.venv) — pip installs land here, nowhere else
python -m pip install --upgrade pip

The REPL: your network calculator

Run python with no arguments and you get the REPL (Read-Evaluate-Print Loop) — an interactive prompt that executes each line as you type it. Network engineers should love the REPL: it is to Python what show commands are to IOS. You poke at things and get immediate answers, no script file required.

🖥 A first REPL session: parsing show output
>>> hostname = "den-core-sw01"
>>> type(hostname)
<class 'str'>
>>> hostname.upper()
'DEN-CORE-SW01'

Three things just happened that deserve names:

  • Assignmenthostname = "den-core-sw01" binds a name to a value. No type declarations; Python infers str from the quotes.
  • Everything is an object — that string carries dozens of built-in behaviors (methods) like .upper(). Discover them with dir(hostname) and read any of them with help(hostname.split).
  • The REPL echoes values — typing an expression prints its result. In a script you’d need print().

Strings: where every parsing job starts

Until you reach structured APIs (much later, in the paid course), device output is text, and text in Python is a string. Four operations cover a shocking amount of real work:

.split() — text in, fields out

>>> line = "Processor board ID FOC2217A0AB"
>>> line.split()
['Processor', 'board', 'ID', 'FOC2217A0AB']
>>> serial = line.split()[3]
>>> serial
'FOC2217A0AB'

.split() with no argument splits on any run of whitespace — which is exactly how CLI output is shaped. Give it a separator to split on something else:

>>> "192.168.10.1".split(".")
['192', '168', '10', '1']

.join() — fields in, text out

>>> octets = ["10", "20", "30", "1"]
>>> ".".join(octets)
'10.20.30.1'

Read it as: the separator joins the list. It looks backwards once, then never again.

.strip() — trust no whitespace

Input from files, prompts, and device output arrives with stray spaces and newlines. .strip() removes leading/trailing whitespace; chain it with other methods to clean as you go:

>>> raw = "  Den-Core-SW01  \n"
>>> raw.strip().lower()
'den-core-sw01'

Membership checks — guard before you parse

>>> line = "Processor board ID FOC2217A0AB"
>>> "Processor board ID" in line
True

in returns a boolean. Once you learn conditionals (Lesson 3), this becomes the guard that keeps your parser from exploding on a line it didn’t expect.

f-strings — output worth reading

Put f before the quotes and {} interpolates variables — with optional formatting after a colon. :^20 centers in 20 characters; < and > align left and right:

>>> hostname, serial = "den-core-sw01", "FOC2217A0AB"
>>> print(f"{hostname:<20} {serial:>15}")
den-core-sw01            FOC2217A0AB

That’s a report column, not just a print statement.

▶ Try it yourself (Python runs in your browser)
Output appears here. First run downloads the Python runtime (~10 MB), so give it a few seconds.

Exercises (graded)

The real practice happens in the lab repo, where every exercise is a small function checked by an automated grader — finish a lesson and you can prove it. From the repo root:

cd labs/python-foundations/lesson01
pytest -q          # red until you do the work — that's the point

You’ll implement five functions in exercises.py:

  1. extract_serial(line) — return the serial from a Processor board ID … line
  2. octets_to_ip(octets) — join a list of four octet strings into dotted-quad
  3. clean_hostname(raw) — strip whitespace and lowercase a hostname
  4. device_row(hostname, ip) — format one fixed-width inventory table row
  5. has_board_id(line) — boolean guard for whether a line carries a serial

Reference solutions live in solutions/ — but run the grader on your own attempt first. Wrong turns are where the learning is.

✅ Check your understanding

You typed device = " nyc-edge-rtr07\n" and need it cleaned and uppercase. Which expression does it?

1 / 3

Summary

Python earns its place in networking because device-by-device work doesn’t scale and text is the raw material of our discipline. You built a virtual environment (your home for the whole course), learned to interrogate objects in the REPL with type(), dir(), and help(), and used the core string toolkit — .split(), .join(), .strip(), membership checks, and f-strings — to pull a serial number out of real show version output and format it for a report. Next lesson: numbers, files, and lists — reading whole configs off disk instead of single lines.