Unless I am missing something, the following Python-alike doesn't work
import strformat
let x=1
echo fmt"{if x > 0 : 7 else: 0}"
neither does
echo fmt"{(if x > 0 : 7 else: 0)}"
Is this a feature? Is there a simple workaround?
Thanks for a hint, Helmut
This works:
echo &"{[0,7][int(x > 7)]}"
I imagine the restriction is related to the {} format options that all involve colons (:), which are a feature. What I would actually do is assign a variable to the result of that conditional.this works:
import std/strformat
let x = 3.14
assert fmt"{(if x!=0: 1.0/x else: 0):.5}" == "0.31847"
assert fmt"{(if true: 1 else: 2)}" == "1"
assert fmt"{if true\: 1 else\: 2}" == "1"
and avoids conflicts with format specifier. See https://github.com/nim-lang/Nim/pull/17700 for more details.
(same answer as https://stackoverflow.com/a/67101278/1426932)
please try to break it! i'm sure there's edge cases I haven't found
curly brackets can also be used, backslash escaped, so that table/json constructors can be used:
import tables,strformat
let (foo,bar) = (3,4)
assert&"""{ toTable( \{"foo": foo, "bar": bar \} ) }""" == """{"foo": 3, "bar": 4}"""