A43 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 3 · Strings, formatting and parsing

From "4.7k" to 4700 and back

Engineers write values with prefixes: 4.7k, 100n, 3.3M. Instruments print readings as text, parts lists arrive as lines of comma-separated fields, and every result you show someone has to be formatted so it's readable. Code spends a surprising amount of its time turning numbers into text and text back into numbers. Python's strings and f-strings make both short, once you know the handful of tools that do the work.

Predict

What does f"{4700:.3g}" produce?

Name it

Strings

A string is text in quotes: "R1", '4.7k'. Useful operations:

CodeResult
s[0], s[-1]first and last character
s[:-1]everything but the last character
len(s)number of characters
s.strip()without spaces at the ends
s.upper(), s.lower()changed case
s.split(",")a list of the pieces between commas
",".join(parts)the pieces joined with commas
s.endswith("k")True or False
float("4.7")the number 4.7
str(4.7)the string "4.7"

Strings can't be changed in place; methods return new strings.

Formatting with f-strings

Inside f"...", anything in braces is evaluated and inserted, with an optional format spec after a colon:

Specx = 4700.0 givesMeans
{x}4700.0plain
{x:.2f}4700.002 digits after the point
{x:.3g}4.7e+033 significant figures
{x:.2e}4.70e+03scientific, 2 after the point
{x:10.1f} 4700.0width 10, right-aligned
{x:,.0f}4,700thousands separators

Engineering prefixes

Python doesn't know SI prefixes, so engineers write two small functions. To format, find the power of 1000 with math.floor(math.log10(abs(x)) / 3), scale, and add the prefix letter. To parse, check the last character against a table of multipliers:

MULT = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "k": 1e3, "M": 1e6, "G": 1e9}

Writing u for micro keeps everything in plain ASCII, as most datasheets and SPICE do.

Worked example

Format 0.0033 A as 3.3 mA.

Show the solution
  1. Find the power of 1000. Take log10⁡, divide by 3 and round down: log10⁡0.0033=−2.48−2.48/3=−0.83 which rounds down to −1.
  2. Scale and pick the prefix. Dividing by 1000−1 gives 3.3, and the prefix for −1 is m.
import math
x = 0.0033
p = math.floor(math.log10(x) / 3)        # log10 is -2.48, /3 is -0.83, floor -1
scaled = x / 1000**p                      # 3.3
prefix = {-4: "p", -3: "n", -2: "u", -1: "m", 0: "", 1: "k", 2: "M", 3: "G"}[p]
print(f"{scaled:.3g} {prefix}A")          # 3.3 mA
  1. Why the floor matters. For 0.0033 the power is −1 (milli), giving a scaled value between 1 and 1000.

Answer the code prints 3.3 mA.

Worked example

Read the line "R7, 4.7k, 1%" into a name, a value in ohms and a tolerance as a fraction.

Show the solution
  1. Split the line and strip the pieces. split breaks the line at commas, and strip removes the spaces.
  2. Drop the last character and convert. Slicing with [:-1] drops the last character (the prefix or the percent sign), then the value is scaled by 1000 and the tolerance divided by 100.
name, val, tol = [p.strip() for p in "R7, 4.7k, 1%".split(",")]
value = float(val[:-1]) * 1e3        # "4.7" times 1000
tolerance = float(tol[:-1]) / 100     # "1" over 100
print(name, value, tolerance)         # R7 4700.0 0.01

Answer the name is R7, the value 4700.0 Ω and the tolerance 0.01.

Check

Write fmt(x, unit) that returns a string with x to three significant figures, a space, then the unit, like fmt(4.567, "V") → "4.57 V". Then set s = fmt(x, "Hz") with x = 4.567.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write eng(x) that returns x scaled to a value from 1 to under 1000, with three significant figures and a prefix letter (p, n, u, m, none, k, M, G), like eng(4700) → "4.7k" and eng(0.0033) → "3.3m". Then set e = eng(v) with v = 0.0033.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write parse(text) that turns a value with an optional prefix letter into a number: parse("4.7k") → 4700, parse("100n") → 1e-07, parse("330") → 330. Then set x = parse(s) for the string s the starter picks.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

A parts list has lines like "R1, 4.7, 5%". The starter builds one for you. Set part (the name), value (a float) and tol (a fraction, so 5% is 0.05).

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

A bench meter answers a query with strings like "+4.71230E+00 VDC": a number in scientific notation, a space, then a unit. Write reading(text) returning (value, unit) with value a float. Then set r = reading(reply) for the reply the starter picks.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What does f"{0.000047:.2e}" produce?

Explain why

Why do engineers write their own eng and parse functions instead of just using print(x) and float(text)?

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.