scan
Builtin index · Collections & strings
result = parse_as(s, template, [must_match=])
Input: s, template, must_match · Output: result
What it is
s and template are Strs. scanf backwards: "hello world 12".parse_as("hello world %d") gives 12. %d a whole number, %f any number, %s a run of non-space, %* anything. The template understands \t, \n, \r and \\ in its literal parts, so "%d\thello" and r"%d\thello" mean the same thing; a literal backslash is doubled.
Overloads
One call shape — this function is not overloaded.
| Code | Input | Output | Description |
result = parse_as(s, template, [must_match=]) | s Strs and template are Strs.template Strs and template are Strs.must_match bool, optionalOptional named must_match (bool, default false) raises an error naming the missing part of the shape instead of returning none — see the limit noted below. | must_match booldefault false | Returns the extracted value (a number, Str, or a List/tuple of them when template has more than one placeholder), or none if the line doesn't have the shape described — never numbers pulled from a different sentence. Optional named must_match (bool, default false) raises an error naming the missing part of the shape instead of returning none — see the limit noted below. |
Examples
From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.
scan("12 goodbye world", "%d hello world", must_match=true)
# error: scan: `%d hello world` did not match `12 goodbye world`
# -- expected ` hello world` after %d
from collections-strings
n = parse_as("hello world 12", "hello world %d")
print(n) # 12
reading = scan("temp = 98.6 F", "temp = %f %s")
print(reading) # (98.6, "F")
print(format(1234.5, "#,##0.0")) # "1,234.5"
print(format(0.256, "0.0%")) # "25.6%"
12 (98.6, "F") 1,234.5 25.6%
from collections-strings
How it works
parse_as(s, template) — scanf backwards, and the reason it exists is that a measurement file's header is a fixed sentence with numbers in it. "hello world 12".parse_as("hello world %d") gives 12. %d a whole number, %f any number, %s a run of non-space, %* anything at all. Literal text between the placeholders must match exactly, which is the point: a line that does not have the shape you said returns none rather than numbers pulled out of a different sentence.
From the note above this builtin in the interpreter, where the reasoning was written down as it was built.
See also
parse_as — documented in the same entry.