Lesson 03: Strings, Text Manipulation & Publication-Grade Engineering Reports
The βBoring Stuffβ Problem: Parsing Messy Sensor Tags and Printing Clean Reports
Mechanical engineers spend half their lives dealing with text, not
just equations: CSV column names full of extra spaces
('Press. (bar)'), PLC part barcodes
("PUMP-CENT-042_316L_15kW"), thermocouple header lines
("T_WALL=412.6C"), and aligning dozens of rows in design
inspection sheets so columns actually line up.
In Python, text is stored as a string
(str)βan ordered sequence of characters inside single
quotes '...' or double quotes "...". Think of
a string like a stamped metal nameplate where every character sits in a
numbered slot starting at index 0!
Core String Mechanics: Indexing, Slicing & Essential Methods
| Technique | Code Example (for
tag = "AISI-4140-ANN") |
Result | Engineering Purpose |
|---|---|---|---|
Index ([0],
[-1]) |
tag[0],
tag[-1] |
'A', 'N' |
Grab first or last character |
Slice ([start:stop]) |
tag[5:9] |
'4140' |
Extract steel grade number
(stop excluded!) |
.strip() |
" 250.4 \n".strip() |
'250.4' |
Remove spaces/tabs/newlines from ends |
.split('-') |
tag.split('-') |
['AISI', '4140', 'ANN'] |
Break delimited part codes into chunks |
.replace(a, b) |
"412.6C".replace("C", "") |
'412.6' |
Clean units before float()
conversion |
.upper() /
.lower() |
"Water".lower() |
'water' |
Case-insensitive fluid lookup |
Watch
Out! Strings Are Text, NOT Numbers ("100" + "50" ->
"10050")
When you read numbers from a text file or user prompt, they arrive as
strings ("42.5"). Adding two strings
concatenates them ("42.5" + "10.0" =
"42.510.0"!). Always clean away units/whitespace and
convert with float() or int() before doing
math. Also remember strings are immutable:
s.strip() returns a new cleaned stringβit does not
modify s unless you reassign
s = s.strip().
# Example 1 (Materials & SCADA Tag Parsing): Turning Raw Instrument Strings into Math
raw_specimen = " SPECIMEN: AISI-1045-CD | Sy=530 MPa | E=205 GPa \n"
cleaned = raw_specimen.strip()
parts = cleaned.split("|") # Splits into 3 fields at '|'
steel_code = parts[0].split(":")[1].strip()
grade_family, grade_num, temper = steel_code.split("-")
# Parse numerical values safely after isolating text after '='
sy_mpa = float(parts[1].split("=")[1].replace("MPa", "").strip())
E_gpa = float(parts[2].split("=")[1].replace("GPa", "").strip())
elastic_strain_limit = (sy_mpa * 1e6) / (E_gpa * 1e9)
print(f"Material Grade : {grade_family} {grade_num} (Condition: {temper})")
print(f"Yield Strength : {sy_mpa:.1f} MPa | Modulus: {E_gpa:.1f} GPa")
print(f"Elastic Strain : {elastic_strain_limit * 1e6:.1f} microstrain")Material Grade : AISI 1045 (Condition: CD)
Yield Strength : 530.0 MPa | Modulus: 205.0 GPa
Elastic Strain : 2585.4 microstrain
Mastering
Modern f-Strings for Alignment & Engineering
Tables
Notice how crisp aligned tables make a design report immediately
readable. Inside {value:format_spec}, you control
everything:
{x:.3f}β Fixed-point float with 3 decimal places (12.346){x:10.2f}β Right-aligned in a column 10 characters wide (12.35){x:<15}β Left-aligned text in a 15-character column{x:.3e}β Scientific notation with 3 decimal places (4.167e-06){pct:.1%}β Multiplies a fraction0.384by100and adds%automatically (38.4%!){n:,}β Thousands separator (1,250,000)
Letβs use these tools on a messy real CSV header from your ME
200 Saturated Water Table
(ME200_Saturated_Water_Temp_Table.csv) and build a clean
steam-property summary printout!
# Example 2 (ME 200 Real Data Cleaning): Fixing Messy Steam Table Headers & Printing Report
from pathlib import Path
# Locate CSV cleanly whether run from module folder or course root
csv_path = next(
p for p in [
Path("datasets/ME200_Saturated_Water_Temp_Table.csv"),
Path("../datasets/ME200_Saturated_Water_Temp_Table.csv"),
] if p.exists()
)
raw_lines = csv_path.read_text(encoding="utf-8").splitlines()
raw_header = raw_lines[0]
print("RAW messy CSV header ->", repr(raw_header[:68] + "..."))
# Clean multiple spaces inside header labels using split() + join()
clean_cols = [" ".join(col.strip().strip('"').split()) for col in raw_header.split('","')]
print("First 3 normalized column names ->", clean_cols[:3])
# Inspect row at 100 degC (search lines simply by string prefix!)
print("\n--- Clean Saturated Steam Checkpoint Report ---")
print(f"{'T [C]':>7} | {'P_sat [bar]':>11} | {'h_f [kJ/kg]':>11} | {'h_g [kJ/kg]':>11} | {'h_fg [kJ/kg]':>12}")
print("-" * 62)
for line in raw_lines[1:6]:
vals = [float(x) for x in line.split(",")]
T_c, P_bar, hf, hg = vals[0], vals[1], vals[4], vals[8]
print(f"{T_c:7.2f} | {P_bar:11.6f} | {hf:11.2f} | {hg:11.1f} | {hg - hf:12.2f}")RAW messy CSV header -> 'Temp. (C),Press. (bar),"Volume (vf, m3/kg)","Internal Energy ...'
First 3 normalized column names -> ['Temp. (C),Press. (bar),"Volume (vf, m3/kg)', 'Internal Energy (uf, kJ/kg)', 'Enthalpy (hf, kJ/kg)']
--- Clean Saturated Steam Checkpoint Report ---
T [C] | P_sat [bar] | h_f [kJ/kg] | h_g [kJ/kg] | h_fg [kJ/kg]
--------------------------------------------------------------
0.01 | 0.006117 | 0.00 | 2500.9 | 2500.90
4.00 | 0.008136 | 16.81 | 2508.2 | 2491.39
5.00 | 0.008726 | 21.02 | 2510.1 | 2489.08
6.00 | 0.009354 | 25.22 | 2511.9 | 2486.68
8.00 | 0.010730 | 33.63 | 2515.6 | 2481.97
Practice Questions (Concept Check)
- For
station = "NOZZLE-THROAT-02", what dostation[:6],station[-2:], andstation.split("-")return? - Why does
int("45.0")raise aValueError, whereasint(float("45.0"))works? - Explain the difference between
{val:>10.2f}and{val:<10.2f}inside anf-string. - Why did
" ".join(text.split())collapse irregular double/triple spaces in theSat_WaterCSV header cleanly?
Guided
Practice Problem 1 (Worked Self-Check): Solar Collector Sensor Packet
Parser (Solar Thermal)
A solar collector test logger transmits telemetry packets formatted
as:
packet = "HR=12 | G_T=915.4 W/m2 | T_amb=29.2 C | T_in=48.0 C | U_L=4.15 W/m2K"
Extract the irradiance \(G_T\),
ambient temperature \(T_{\text{amb}}\),
fluid inlet temperature \(T_{\text{in}}\), and overall loss
coefficient \(U_L\) as floats, compute
the collector useful efficiency using \(F_R =
0.89\), \((\tau\alpha)_e =
0.82\): \[\eta_c = F_R
\left[(\tau\alpha)_e - U_L \frac{T_{\text{in}} -
T_{\text{amb}}}{G_T}\right]\] and print a single aligned summary
report using % formatting.
Hint: Split on β|β, then split each chunk on β=β
Strip units (W/m2K, W/m2, C)
before calling float(), and format efficiency with
f"{eta:.2%}".
# Worked Practice Problem 1 Solution: Telemetry Packet -> HWB Solar Efficiency
packet = "HR=12 | G_T=915.4 W/m2 | T_amb=29.2 C | T_in=48.0 C | U_L=4.15 W/m2K"
fields = {}
for item in packet.split("|"):
key, val_str = [x.strip() for x in item.split("=")]
num_token = val_str.split()[0] # Grabs leading number before unit text!
fields[key] = float(num_token)
F_R, tau_alpha = 0.89, 0.82
eta_c = F_R * (tau_alpha - fields["U_L"] * (fields["T_in"] - fields["T_amb"]) / fields["G_T"])
print(f"Solar Hour {int(fields['HR']):02d}:00 | G_T = {fields['G_T']:.1f} W/m^2")
print(f"Delta T / G_T = {(fields['T_in'] - fields['T_amb'])/fields['G_T']:.4f} K*m^2/W")
print(f"Collector Efficiency eta_c = {eta_c:.2%}")Solar Hour 12:00 | G_T = 915.4 W/m^2
Delta T / G_T = 0.0205 K*m^2/W
Collector Efficiency eta_c = 65.39%
End-of-Chapter Practice Problems (Try Yourself!)
- Thermocouple Channel Cleaner: Parse
" CH04 | T_WALL = 384.7 K | HEAT_FLUX = 42.5 kW/m2 "into channel name (str),T_wall_c(float), andq_w_m2(float), then print a formatted badge showing temperature in bothdegCandK. - Fluid Pipe Schedule Formatter: Given raw pipe specs
"SCH40-DN100-L=45.0m-EPS=0.045mm", extract nominal diameterDN(mm), length (m), and roughness (mm) using.split("-"), compute \(\varepsilon / D\), and print \(\varepsilon / D\) in scientific notation ({val:.2e}). - Turbomachinery Spec Table Header Generator: Print a
neatly boxed 5-row header for an Axial Compressor Test Matrix
(
Stage,r_p,T_in [K],T_out [K],Isentropic Eff) using string center/left/right alignment (^,<,>).