---
title: Strings, formatting and parsing values
heading: From "4.7k" to 4700 and back
eyebrow: A4 · Lesson 3 · Strings, formatting and parsing
xp: 40
---

::: hook
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?

- [ ] `"4700.000"`
- [x] `"4.7e+03"`
- [ ] `"4.70k"`
- [ ] `"4700"`

::: reveal
`"4.7e+03"`. The `g` format keeps three significant figures and switches to scientific notation when the exponent is at least the precision (here, 3). It never adds an engineering prefix: that's a function you'll write in this lesson.
:::
:::

::: nameit
## Strings

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

| Code | Result |
|---|---|
| `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:

| Spec | `x = 4700.0` gives | Means |
|---|---|---|
| `{x}` | `4700.0` | plain |
| `{x:.2f}` | `4700.00` | 2 digits after the point |
| `{x:.3g}` | `4.7e+03` | 3 significant figures |
| `{x:.2e}` | `4.70e+03` | scientific, 2 after the point |
| `{x:10.1f}` | `    4700.0` | width 10, right-aligned |
| `{x:,.0f}` | `4,700` | thousands 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.
:::

::: example
## Format 0.0033 A as `3.3 mA`.

::: solution
1. **Find the power of 1000.** Take $\log_{10}$, divide by 3 and round down:
   $$\begin{aligned} \log_{10} 0.0033 &= -2.48 \\ -2.48/3 &= -0.83 \end{aligned}$$
   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
```

3. **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`.
:::
:::

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

::: 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
kind: python
given: x = 0.0123 | 4.567 | 1234.5 | 98765.4

## 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` = {x}.

```python starter
def fmt(x, unit):
    return str(x) + unit

s = fmt(x, "Hz")
print(s)
```

```python solution
def fmt(x, unit):
    return f"{x:.3g} {unit}"

s = fmt(x, "Hz")
print(s)
```

```python tests
assert fmt(4.567, "V") == "4.57 V", f'fmt(4.567, "V") should be "4.57 V", but it gave {fmt(4.567, "V")!r}. Use an f-string with :.3g and a space.'
assert fmt(0.5, "A") == "0.5 A", 'fmt(0.5, "A") should be "0.5 A".'
assert s == f"{x:.3g} Hz", "s doesn't match for this lab's x."
```

::: right
Right. `.3g` rounds to three significant figures and drops trailing zeros.
:::
:::

::: check
kind: python
given: v = 4700 | 0.0033 | 2.2e-9 | 1.5e6 | 47e-6

## 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` = {v}.

```python starter
import math

def eng(x):
    return f"{x:.3g}"

e = eng(v)
print(e)
```

```python solution
import math

def eng(x):
    p = math.floor(math.log10(abs(x)) / 3)
    prefix = {-4: "p", -3: "n", -2: "u", -1: "m", 0: "", 1: "k", 2: "M", 3: "G"}[p]
    return f"{x / 1000**p:.3g}{prefix}"

e = eng(v)
print(e)
```

```python tests
assert eng(4700) == "4.7k", f'eng(4700) should be "4.7k", but it gave {eng(4700)!r}.'
assert eng(0.0033) == "3.3m", f'eng(0.0033) should be "3.3m", but it gave {eng(0.0033)!r}. Use math.floor so negative powers round down.'
assert eng(5) == "5", 'eng(5) should be "5", with no prefix.'
assert eng(2.2e-9) == "2.2n", 'eng(2.2e-9) should be "2.2n".'
```

::: right
Right. `floor(log10(x) / 3)` picks the power of 1000, and the rest is a lookup.
:::
:::

::: check
kind: python
given: k = 0..4 int

## 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 starter
MULT = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "k": 1e3, "M": 1e6, "G": 1e9}

def parse(text):
    return float(text)

s = ["4.7k", "100n", "2.2M", "330", "15u"][k]
x = parse(s)
print(s, x)
```

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

def parse(text):
    text = text.strip()
    if text[-1] in MULT:
        return float(text[:-1]) * MULT[text[-1]]
    return float(text)

s = ["4.7k", "100n", "2.2M", "330", "15u"][k]
x = parse(s)
print(s, x)
```

```python tests
import math
assert math.isclose(parse("4.7k"), 4700), 'parse("4.7k") should be 4700.'
assert math.isclose(parse("100n"), 1e-7), 'parse("100n") should be 1e-07.'
assert math.isclose(parse("330"), 330), 'parse("330") should be 330: no prefix means a plain number.'
assert math.isclose(parse(" 2.2M "), 2.2e6), 'parse(" 2.2M ") should be 2200000. Strip the spaces first.'
```

::: right
Right. Check the last character against the table, and fall back to a plain number.
:::
:::

::: check
kind: python
given: k = 0..2 int; v = 4.7 | 22 | 330; t = 1 | 5 | 10

## 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 starter
name = ["R1", "C3", "L2"][k]
line = f"{name}, {v}, {t}%"
part = line
value = 0.0
tol = 0.0
print(part, value, tol)
```

```python solution
name = ["R1", "C3", "L2"][k]
line = f"{name}, {v}, {t}%"
part, val, pct = [p.strip() for p in line.split(",")]
value = float(val)
tol = float(pct[:-1]) / 100
print(part, value, tol)
```

```python tests
import math
assert part == ["R1", "C3", "L2"][k], f"part should be {['R1', 'C3', 'L2'][k]!r}. Split the line at the commas and strip the spaces."
assert math.isclose(value, v), "value should be the number in the middle field."
assert math.isclose(tol, t / 100), "tol should be a fraction: drop the % and divide by 100."
```

::: right
Right. Split, strip, convert: most text formats come apart with those three steps.
:::
:::

::: check
kind: python
given: k = 0..3 int

## 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 starter
replies = ["+4.71230E+00 VDC", "-1.20050E-03 ADC", "+9.99870E+03 OHM", "+5.00012E+01 HZ"]
reply = replies[k]

def reading(text):
    return text, ""

r = reading(reply)
print(r)
```

```python solution
replies = ["+4.71230E+00 VDC", "-1.20050E-03 ADC", "+9.99870E+03 OHM", "+5.00012E+01 HZ"]
reply = replies[k]

def reading(text):
    number, unit = text.strip().split()
    return float(number), unit

r = reading(reply)
print(r)
```

```python tests
want = [(4.7123, "VDC"), (-1.2005e-3, "ADC"), (9998.7, "OHM"), (50.0012, "HZ")][k]
assert isinstance(r, tuple) and len(r) == 2, "reading should return a pair (value, unit)."
assert isinstance(r[0], float) and abs(r[0] - want[0]) <= 1e-12 * abs(want[0]), f"The value should be {want[0]}: float() reads E notation directly."
assert r[1] == want[1], f"The unit should be {want[1]!r}."
assert reading("  -2.5E-06 ADC\n") == (-2.5e-6, "ADC"), "Strip spaces and the newline an instrument sends before splitting."
```

::: right
Right. `split()` with no argument splits on any run of spaces, and `float` reads `E` notation as it stands. Stripping first copes with the line ending every instrument sends.
:::
:::

::: check
kind: choice

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

- [x] `'4.70e-05'`
- [ ] `'4.7e-05'`
- [ ] `'0.00'`
- [ ] `'47.00e-06'`

::: right
Right. `e` format writes one digit before the point, `.2` asks for two after it (so the trailing 0 stays), and the exponent is whatever makes that work, here −5.
:::

::: misses
- [2] `.2` asks for exactly two digits after the point, so the trailing zero is kept: `4.70`.
- [3] That's what `.2f` would give. `e` switches to scientific notation.
- [4] That's engineering notation, which `e` format doesn't do. It always puts one digit before the point.
:::
:::

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

::: model
Python's built-in formatting and conversion only understand plain numbers and scientific notation, while engineers read and write values with SI prefixes like 4.7k and 100n. `float("4.7k")` raises an error, and `print(0.0033)` doesn't show 3.3m. Two short functions bridge the gap, converting between the prefix form people use and the plain numbers in base units that calculations need.
:::
:::

::: practice

::: check
kind: python
given: x = 0.000123 | 12345.6789 | 3.14159

## Set `s` to `x` = {x} in scientific notation with two digits after the point, like `"1.23e-04"`.

```python starter
s = str(x)
print(s)
```

```python solution
s = f"{x:.2e}"
print(s)
```

```python tests
assert s == f"{x:.2e}", "Use the format spec :.2e."
```
:::

::: check
kind: python
given: a = 1 | 2 | 5; b = 10 | 20; c = 3 | 7

## Set `line` to the three numbers `a` = {a}, `b` = {b} and `c` = {c} joined with commas and no spaces, like `"1,10,3"`.

```python starter
line = ""
print(line)
```

```python solution
line = ",".join(str(n) for n in [a, b, c])
print(line)
```

```python tests
assert line == f"{a},{b},{c}", f"line should be {a},{b},{c}. Turn each number into a string and join with commas."
```
:::

::: check
kind: python
given: k = 0..3 int

## Set `has_prefix` to whether the string `s` the starter picks ends in a letter.

```python starter
s = ["47k", "2.2M", "680", "15u"][k]
has_prefix = None   # True or False
print(s, has_prefix)
```

```python solution
s = ["47k", "2.2M", "680", "15u"][k]
has_prefix = s[-1].isalpha()
print(s, has_prefix)
```

```python tests
assert has_prefix == ["47k", "2.2M", "680", "15u"][k][-1].isalpha(), "Look at the last character: s[-1].isalpha() tells you if it's a letter."
```
:::
:::
