Python Session 03: Strings

String mastery. This session covers string methods, f-string formatting, and regex patterns.

Pre-Session State

  • Can read/write files

  • Understand JSON and CSV handling

  • Know pathlib basics

Setup

# Test data
log_line = "2026-03-18T10:30:45 INFO [kvm-01] Server started on 10.50.1.110:443"
mac_address = "AA:BB:CC:11:22:33"

Lesson 1: String Methods

Concept: Strings have many built-in methods for manipulation.

Exercise 1.1: Case conversion

hostname = "Kvm-01"
print(hostname.lower())     # kvm-01
print(hostname.upper())     # KVM-01
print(hostname.title())     # Kvm-01
print(hostname.capitalize())  # Kvm-01

Exercise 1.2: Split and join

fqdn = "kvm-01.inside.domusdigitalis.dev"
parts = fqdn.split('.')
print(parts)  # ['kvm-01', 'inside', 'domusdigitalis', 'dev']

hostname = parts[0]
domain = '.'.join(parts[1:])
print(f"Host: {hostname}, Domain: {domain}")

Exercise 1.3: Strip and replace

line = "  kvm-01  \n"
print(repr(line.strip()))    # 'kvm-01'
print(repr(line.lstrip()))   # 'kvm-01  \n'
print(repr(line.rstrip()))   # '  kvm-01'

ip = "10.50.1.110"
print(ip.replace('.', '-'))  # 10-50-1-110

Exercise 1.4: Testing strings

hostname = "kvm-01"
print(hostname.startswith('kvm'))  # True
print(hostname.endswith('-01'))     # True
print('kvm' in hostname)            # True

port = "443"
print(port.isdigit())  # True

Lesson 2: F-Strings (Advanced)

Concept: F-strings support expressions and formatting.

Exercise 2.1: Expressions in f-strings

hosts = ["kvm-01", "kvm-02"]
print(f"Count: {len(hosts)}")
print(f"First: {hosts[0].upper()}")
print(f"Active: {2 > 1}")

Exercise 2.2: Number formatting

cpu = 85.6789
print(f"CPU: {cpu:.2f}%")      # 85.68
print(f"CPU: {cpu:>10.2f}%")   # Padded

count = 1234567
print(f"Count: {count:,}")     # 1,234,567

port = 22
print(f"Port: {port:05d}")     # 00022

Exercise 2.3: Alignment

name = "kvm-01"
ip = "10.50.1.110"
print(f"{name:<15} {ip:>15}")  # Left, right align
print(f"{name:^20}")           # Center

Exercise 2.4: Debug format (3.8+)

hostname = "kvm-01"
vlan = 10
print(f"{hostname=}, {vlan=}")  # hostname='kvm-01', vlan=10

Lesson 3: Regular Expressions

Concept: Use re module for pattern matching.

Exercise 3.1: Basic matching

import re

text = "Server IP is 10.50.1.110"
if re.search(r'\d+\.\d+\.\d+\.\d+', text):
    print("Found an IP address")

match = re.search(r'(\d+\.\d+\.\d+\.\d+)', text)
if match:
    print(f"IP: {match.group(1)}")

Exercise 3.2: Find all matches

import re

log = "Connections from 10.50.1.100, 10.50.1.101, 10.50.1.102"
ips = re.findall(r'\d+\.\d+\.\d+\.\d+', log)
print(ips)  # ['10.50.1.100', '10.50.1.101', '10.50.1.102']

Exercise 3.3: Substitution

import re

text = "Password: secret123"
redacted = re.sub(r'Password: \S+', 'Password: <REDACTED>', text)
print(redacted)

Exercise 3.4: Named groups

import re

log = "2026-03-18T10:30:45 ERROR [kvm-01] Connection refused"
pattern = r'(?P<time>\S+) (?P<level>\w+) \[(?P<host>\w+-\d+)\] (?P<msg>.+)'

match = re.match(pattern, log)
if match:
    print(f"Time: {match.group('time')}")
    print(f"Level: {match.group('level')}")
    print(f"Host: {match.group('host')}")
    print(f"Message: {match.group('msg')}")

Summary: What You Learned

Concept Syntax Example

Split

str.split(sep)

"a.b.c".split('.')['a','b','c']

Join

sep.join(list)

'.'.join(['a','b'])'a.b'

F-string format

{var:.2f}

f"{3.14159:.2f}"'3.14'

Alignment

{var:<10}

f"{x:<10}" left-pad to 10

re.search

re.search(pattern, text)

Returns match object

re.findall

re.findall(pattern, text)

Returns list of matches

re.sub

re.sub(pat, repl, text)

Replace matches

Exercises to Complete

  1. [ ] Parse log line to extract timestamp, level, host, message

  2. [ ] Find all MAC addresses in a string (AA:BB:CC:DD:EE:FF format)

  3. [ ] Format a table of hosts with aligned columns

  4. [ ] Redact all IP addresses in a log file

Next Session

Session 04: Functions - def, lambda, classes, dataclasses.

Session Log

Timestamp Notes

Start

<Record when you started>

End

<Record when you finished>