Python f-strings: expressions and format specs
An f-string evaluates expressions and applies format specs. TE-32-A shows one f-string with an addition and a .2f spec. TE-32-B adds the !r conversion, a .3f spec and zero padding.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-32-A: f-strings evaluate expressions and apply format specs
Setup for this run, inside a throwaway directory (mktemp -d):
printf 'a = 2\nb = 3\nprint(f"{a + b} {a / b:.2f}")\n' > s.pyCommand:
python3 s.pyRecorded output:
5 0.67TE-32-B: an f-string can use the !r conversion, the .3f spec and zero padding
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
python3 -c "name='x'; print(f'{name!r} {3.14159:.3f} {5:03d}')"Recorded output:
'x' 3.142 005Exit status: 0. This status and the output match what was written before the run.
TE-32-C: expected non-zero exit: an f-string that names an undefined variable raises NameError
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
python3 -c "print(f'{nosuch}')"Recorded output: none, standard output was empty.
Standard error from the same run:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'nosuch' is not definedExit status: 1. This status and the output match what was written before the run.
TE-32-B: the f-string printed 'x' for the !r conversion of the text x, 3.142 for 3.14159 with the .3f spec, and 005 for 5 with the 03d spec. TE-32-C: the name nosuch is not defined, so the f-string stopped with exit status 1. The last line of standard error is NameError: name 'nosuch' is not defined.
Limits
TE-32-A shows one f-string, and TE-32-B three more pieces of format syntax. Function definitions, nested quotes and other format specs are not tested here.
Source
Evidence
TE-32-A: f-strings evaluate expressions and apply format specs
- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-32-A | f-strings evaluate expressions and apply format specs | 0 | PASS | 6b7d2d5cbf20 | | TE-32-B | an f-string can use the !r conversion, the .3f spec and zero padding | 0 | PASS | e6faba2af7e4 | | TE-32-C | expected non-zero exit: an f-string that names an undefined variable raises NameError | 1 | PASS | 8a8093a4aeb4 |
Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides