Python Strings – Working with Text That Actually Makes Sense
Right, so that’s variables sorted. You can stick information in them, you understand the different types, brilliant. Now we need to look at working with text properly – what Python calls strings.
You’ve already been using strings without realising it. Every time you’ve typed something like hostname = "SW1-ACCESS"
, that bit in quotes is a string. But there’s loads more to strings than just sticking text in quotes.
Python for Network Engineers Blog 7: Python Variables
Look, most of the stuff we work with every day is text, isn’t it? Device hostnames, interface descriptions, configuration commands, log entries. All text. Python’s got some brilliant features for handling text that’ll make your life much easier.
Now, most programming courses teach strings using people’s names and addresses and all that rubbish. I’m sitting there thinking, that’s lovely mate, but I’ve got fifty switches to configure. How’s knowing Dave’s favourite colour going to help me with VLAN automation then? It’s not, is it?
So what we’ll do, we’ll learn strings using device names and interface configs and actual network stuff that makes sense.
What Strings Actually Are
A string is just a sequence of characters. Letters, numbers, spaces, symbols – anything you can type gets treated as text when you put it in quotes.
hostname = "SW1-ACCESS"
description = "Building A Access Switch"
interface = "GigabitEthernet0/1"
Each of those variables contains a string. Python knows they’re strings because of the quotes.
Thing is, strings are for storing text you want to display or work with. Not for calculations – that’s what numbers are for.
When you’re documenting your network, you write down device names, interface descriptions, site locations. That’s all text information, isn’t it? Strings let you store and work with that same stuff in Python.
Single or Double Quotes
Python doesn’t care whether you use single quotes or double quotes:
hostname1 = "SW1-ACCESS" # Double quotes
hostname2 = 'SW2-ACCESS' # Single quotes
Both do exactly the same thing. Most people use double quotes, but it’s your choice. Just be consistent.
Why would you pick one over the other? Sometimes your text has quotes in it:
description = "Building A 'main' switch"
command = 'show interface "GigabitEthernet0/1"'
Much easier than messing about with escape characters.
Storing Network Information
Let’s look at storing proper network information:
# Device information
hostname = "R1-EDGE-RTR"
location = "Main Office Edge"
device_type = "Router"
# Interface details
interface_name = "GigabitEthernet0/1"
interface_desc = "Uplink to ISP"
interface_status = "up"
# Network addressing
network_range = "10.1.1.0/24"
gateway_ip = "10.1.1.1"
See? We’re storing the same type of information you’d put in a network diagram. Hostnames, descriptions, IP ranges – all as strings.
Much more relevant than storing someone’s first name and last name.
VLAN Information
# VLAN configurations
sales_vlan = "10"
engineering_vlan = "20"
guest_vlan = "30"
# VLAN names
sales_name = "Sales Department"
engineering_name = "Engineering Team"
guest_name = "Guest Access"
Now you might be wondering why I’m storing VLAN numbers as strings instead of integers. Good question. In this case, we’re treating them as identifiers rather than numbers we’ll do maths with. Depends what you’re planning to do with them.
Joining Strings Together
One of the most useful things you can do is stick strings together. Python calls this concatenation, but it’s just joining text.
Use the +
operator:
hostname = "SW1"
suffix = "-ACCESS"
full_hostname = hostname + suffix
print(full_hostname) # SW1-ACCESS

Let’s try something more useful:
# Build interface descriptions
location = "Building A"
department = "Sales"
description = location + " " + department + " Access Port"
print(description) # Building A Sales Access Port
Notice I had to add the spaces manually. Python doesn’t add spaces automatically when joining strings.

Building Configuration Commands
This is where string joining becomes really useful:
interface = "GigabitEthernet0/2"
vlan = "10"
description = "Sales Department Port"
# Build the configuration
config_line1 = "interface " + interface
config_line2 = "description " + description
config_line3 = "switchport access vlan " + vlan
print(config_line1)
print(config_line2)
print(config_line3)
Output:
interface GigabitEthernet0/2
description Sales Department Port
switchport access vlan 10

That’s proper configuration text you could paste into a switch. Much more useful than joining someone’s first and last name together.
Repeating Strings
Python lets you repeat strings using the *
operator:
banner_line = "=" * 40
print(banner_line) # ========================================
separator = "-" * 20
print(separator) # --------------------
Brilliant for creating separators in output:
print("Network Device Status")
print("=" * 25)
print("SW1-ACCESS: Online")
print("SW2-ACCESS: Online")
print("R1-EDGE-RTR: Online")
print("=" * 25)
Much cleaner than typing out loads of equals signs manually.
Creating Configuration Blocks
hostname = "SW1-ACCESS"
comment_line = "!" * 50
print(comment_line)
print("! Configuration for " + hostname)
print(comment_line)
Creates nice headers for configuration files.
F-Strings – Much Better Way
We touched on f-strings when we covered print, didn’t we? But they’re so useful they deserve proper coverage.
F-strings let you insert variables directly into text. Put f
before the quotes and use curly braces:
hostname = "SW1-ACCESS"
vlan_id = 10
message = f"Device {hostname} is configured for VLAN {vlan_id}"
print(message) # Device SW1-ACCESS is configured for VLAN 10
Much cleaner than using +
operators everywhere.
Building Interface Configurations
interface = "GigabitEthernet0/2"
vlan = 10
description = "Sales Department"
config = f"""interface {interface}
description {description}
switchport mode access
switchport access vlan {vlan}
spanning-tree portfast"""
print(config)
That’s a complete interface configuration built from variables. Dead useful.

Status Messages
device = "R1-EDGE-RTR"
cpu_usage = 15.7
status = f"Device {device} CPU utilisation: {cpu_usage}%"
print(status) # Device R1-EDGE-RTR CPU utilisation: 15.7%
Perfect for monitoring scripts and status reports.
Common Mistakes Everyone Makes
I see people make the same mistakes with strings all the time.
Forgetting Quotes
hostname = SW1-ACCESS # Error - Python thinks SW1-ACCESS is a variable
hostname = "SW1-ACCESS" # Right - quotes make it a string
Without quotes, Python thinks you’re referring to a variable. With quotes, it knows you mean the actual text.
Mixing Strings and Numbers
vlan_id = 10 # Number
vlan_name = "Sales" # String
# This won't work
config = "vlan " + vlan_id # Error - can't add string and number
# This works
config = "vlan " + str(vlan_id) # Convert number to string first
# This is better
config = f"vlan {vlan_id}" # F-string handles conversion
F-strings automatically convert numbers to text, which is why they’re so useful.
Trying to Change Strings
hostname = "SW1-ACCESS"
hostname[0] = "R" # Error - can't change individual characters
Strings are immutable in Python. You can’t change them after creation. You have to create a new string instead.
Don’t worry about that slicing stuff yet – we’ll cover that properly later.
Working with Device Information
Let’s look at some realistic examples.
Device Inventory
# Device information
router1_hostname = "R1-EDGE-RTR"
router1_model = "CSR1000v"
router1_location = "Main Office"
switch1_hostname = "SW1-ACCESS"
switch1_model = "IOSvL2"
switch1_location = "Building A"
# Create inventory descriptions
router1_info = f"{router1_hostname} ({router1_model}) - {router1_location}"
switch1_info = f"{switch1_hostname} ({switch1_model}) - {switch1_location}"
print("Network Inventory:")
print(router1_info)
print(switch1_info)
Output:
Network Inventory:
R1-EDGE-RTR (CSR1000v) - Main Office
SW1-ACCESS (IOSvL2) - Building A
Interface Documentation
# Interface information
interface = "GigabitEthernet0/1"
connected_device = "SW1-ACCESS"
connection_type = "Trunk"
vlans_allowed = "10,20,30,99"
# Build interface description
description = f"Connection to {connected_device} - {connection_type} - VLANs {vlans_allowed}"
print(f"interface {interface}")
print(f"description {description}")
VLAN Configuration
# VLAN details
vlan_id = "10"
vlan_name = "Sales"
subnet = "10.1.10.0/24"
gateway = "10.1.10.1"
# Create VLAN configuration
vlan_config = f"""vlan {vlan_id}
name {vlan_name}
!
interface vlan {vlan_id}
description {vlan_name} Gateway - {subnet}
ip address {gateway} 255.255.255.0
no shutdown"""
print(vlan_config)
That generates proper VLAN configuration you could use on actual switches.
String Operations for Network Tasks
Here’s how string operations help with actual network stuff.
Standardising Hostnames
# Raw hostname input
raw_hostname = "sw1access"
# Standardise the format
site_code = "SW1"
function = "ACCESS"
standard_hostname = site_code + "-" + function
print(f"Standardised hostname: {standard_hostname}") # SW1-ACCESS
Building Configuration Headers
hostname = "SW1-ACCESS"
date = "2024-01-15"
engineer = "Network Team"
# Create configuration header
header = f"""!
! Configuration for {hostname}
! Generated: {date}
! Engineer: {engineer}
!
{'-' * 50}
"""
print(header)
Command Templates
# Interface configuration template
interface_template = "interface {}"
description_template = "description {}"
vlan_template = "switchport access vlan {}"
# Apply to specific interface
interface_num = "GigabitEthernet0/2"
port_desc = "Sales Workstation"
access_vlan = "10"
print(interface_template.format(interface_num))
print(description_template.format(port_desc))
print(vlan_template.format(access_vlan))
Though f-strings are usually cleaner for this sort of thing.
Why This Actually Matters
Every automation script you’ll write deals with text. Configuration files, command outputs, log entries, device responses – it’s all text that needs processing.
Understanding strings properly means you can parse show command outputs to extract specific information, generate configuration files from templates, process log files to find specific events, build standardised device documentation, create reports from network data.
Without solid string handling, automation becomes much harder.
Processing Interface Status
# Simulated show command output
interface_status = "GigabitEthernet0/1 is up, line protocol is up"
# Extract key information
if "is up" in interface_status:
if "line protocol is up" in interface_status:
status = "Interface fully operational"
else:
status = "Interface has issues"
else:
status = "Interface is down"
print(f"Status: {status}")
This type of text processing is fundamental to network automation and dont worry yet about the if and else statements now as we will go through their usage in a later blog..
Building Good Habits
Start developing good habits with strings now and you’ll write cleaner code later.
Use descriptive variable names:
# Poor - unclear what these contain
s1 = "SW1-ACCESS"
s2 = "Building A"
# Good - obvious what each contains
hostname = "SW1-ACCESS"
location = "Building A"
Use f-strings for formatting:
# Avoid concatenation when f-strings are cleaner
message = hostname + " is located in " + location # Works but messy
# Use f-strings instead
message = f"{hostname} is located in {location}" # Much cleaner
Be consistent with quote style:
# Pick single or double quotes and stick with it
hostname = "SW1-ACCESS"
location = "Building A"
device_type = "Switch"
Consistency makes your code easier to read.
What’s Coming Next
You understand strings now. How to create them, join them together, repeat them, and use them for storing network information. This gives you the text handling skills needed for working with device data.
Next we’ll look at Python integers – numbers you can do calculations with. Port counts, VLAN numbers, IP address octets, bandwidth calculations. All the numerical stuff that goes alongside the text information you’re now comfortable handling.
The combination of strings and numbers gives you the basic data types needed for most network automation tasks. Master these fundamentals and you’re well on your way to writing useful scripts.
For now, practice working with strings using actual network information. Device hostnames, interface descriptions, configuration commands. Get comfortable storing and manipulating text the way you’ll actually use it in real network automation.
External Link: Python String Documentation – official Python documentation for string operations and methods
Pingback: Python for Network Engineers Blog 9: Python Integers - RichardKilleen