Lesson
05: Strings, Cleaning Dirty Field Telemetry & f-String
Compliance Tables
The โBoring Stuffโ Problem: Manually Re-Typing Sensor Text Logs Into Columns
Real environmental loggers donโt hand you clean floating-point
numbers. Field sondes and air sensors emit messy text like:
" STATION: WAB-04 | O3=0.068 ppmv | TEMP=28.5 C | QA_STATUS=ok "
or European semicolon strings like
"10/03/2004;18.00.00;2,6;1360;150;11,9;" (literally how
UCI_Air_Quality_Italy_Hourly.csv stores
every hour!).
Think of a Python string s as an unchangeable
chain of characters equipped with power-tools:
.strip()removes leading/trailing spaces and newline\nclutter..split("|")chops one long string into a neat Python list at every delimiter..replace(",", ".")swaps European decimal commas into Python decimal dots sofloat("11,9")wonโt crash withValueError!f"{value:8.2f}"formats numbers right-aligned into crisp, publication-grade regulatory tables.
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
# Example 1: Automated Parsing of a Messy Air-Monitoring Telemetry Packet
raw_packet = " SITE: ST-04_URBAN | O3=0.074 ppm | T=31.0 C | P=0.96 atm | STATUS=valid \n"
# Chain .strip() and .split("|") cleanly
parts = [item.strip() for item in raw_packet.strip().split("|")]
site_id = parts[0].split(":")[1].strip()
o3_ppm = float(parts[1].split("=")[1].replace("ppm", "").strip())
temp_c = float(parts[2].split("=")[1].replace("C", "").strip())
pres_atm = float(parts[3].split("=")[1].replace("atm", "").strip())
# Ideal Gas Law conversion: C_ug_m3 = ppm * 1000 * MW * P / (R * T_K)
mw_o3 = 48.00
R_atm = 0.082057
o3_ug_m3 = o3_ppm * 1000.0 * mw_o3 * pres_atm / (R_atm * (temp_c + 273.15))
print("=== Parsed Ambient Air Packet ===")
print(f"Station ID : {site_id}")
print(f"Raw Mixing : {o3_ppm:.3f} ppmv (EPA 8-hr Limit = 0.070 ppmv)")
print(f"Mass Density : {o3_ug_m3:.2f} ug/m^3 at {temp_c:.1f} C, {pres_atm:.2f} atm")
print(f"Compliance : {'EXCEEDANCE' if o3_ppm > 0.070 else 'COMPLIANT'}")=== Parsed Ambient Air Packet ===
Station ID : ST-04_URBAN
Raw Mixing : 0.074 ppmv (EPA 8-hr Limit = 0.070 ppmv)
Mass Density : 136.63 ug/m^3 at 31.0 C, 0.96 atm
Compliance : EXCEEDANCE
# Example 2 (Real UCI Data Parsing!): Handling European Comma Decimals in UCI_Air_Quality_Italy_Hourly.csv
aq_lines = data_file("UCI_Air_Quality_Italy_Hourly.csv").read_text(encoding="utf-8").splitlines()
print("Raw UCI Row 0:", aq_lines[0])
print("Raw UCI Row 1:", aq_lines[1])
print("\nDate | Hour | CO [mg/m^3] | Benzene [ug/m^3] | NO2 [ug/m^3] | Temp [C]")
print("-" * 80)
for raw_row in aq_lines[1:6]:
cols = raw_row.split(";")
date_s, time_s = cols[0], cols[1]
co_val = float(cols[2].replace(",", "."))
c6h6_val = float(cols[5].replace(",", "."))
no2_val = float(cols[9].replace(",", "."))
temp_val = float(cols[12].replace(",", "."))
print(f"{date_s:<10s} | {time_s:<8s} | {co_val:11.2f} | {c6h6_val:16.2f} | {no2_val:12.1f} | {temp_val:8.1f}")Raw UCI Row 0: Date;Time;CO(GT);PT08.S1(CO);NMHC(GT);C6H6(GT);PT08.S2(NMHC);NOx(GT);PT08.S3(NOx);NO2(GT);PT08.S4(NO2);PT08.S5(O3);T;RH;AH;;
Raw UCI Row 1: 10/03/2004;18.00.00;2,6;1360;150;11,9;1046;166;1056;113;1692;1268;13,6;48,9;0,7578;;
Date | Hour | CO [mg/m^3] | Benzene [ug/m^3] | NO2 [ug/m^3] | Temp [C]
--------------------------------------------------------------------------------
10/03/2004 | 18.00.00 | 2.60 | 11.90 | 113.0 | 13.6
10/03/2004 | 19.00.00 | 2.00 | 9.40 | 92.0 | 13.3
10/03/2004 | 20.00.00 | 2.20 | 9.00 | 114.0 | 11.9
10/03/2004 | 21.00.00 | 2.20 | 9.20 | 122.0 | 11.0
10/03/2004 | 22.00.00 | 1.60 | 6.50 | 116.0 | 11.2
Concept Check Questions
- Why does
float("2,6")fail in Python until you run.replace(",", ".")? - What does
.strip()remove besides regular spaces? - Explain each part of
f"{val:10.3f}": what do10,.3, andfcontrol?
Guided Practice Problem 1: Parse Messy Groundwater Nitrate Lab String
Given
lab_str = " WELL-MW12 | NO3_N=11.45_mg/L | Cl=42.8_mg/L | pH=6.94 ",
write string-cleaning Python code to extract well,
no3_mgL, cl_mgL, and ph, then
check if no3_mgL > 10.0 (EPA Drinking Water MCL = \(10.0\text{ mg/L}\) as N).
# Guided Practice 1 Starter
lab_str = " WELL-MW12 | NO3_N=11.45_mg/L | Cl=42.8_mg/L | pH=6.94 "
tokens = [t.strip() for t in lab_str.strip().split("|")]
well = tokens[0]
no3_mgL = float(tokens[1].split("=")[1].replace("_mg/L", ""))
print(f"{well}: Nitrate-N = {no3_mgL:.2f} mg/L -> Exceeds 10 mg/L EPA MCL? {no3_mgL > 10.0}")WELL-MW12: Nitrate-N = 11.45 mg/L -> Exceeds 10 mg/L EPA MCL? True