2Cubed 2Cubed - 3 months ago 23
Python Question

Julia string format "if"

In Python,

if
may be used in a situation such as the following for optional string formatting.

bar = 3
"{n} bar{s}".format(n=bar, s='s' if bar != 1 else '')
# "3 bars"

bar = 1
"{n} bar{s}".format(n=bar, s='s' if bar != 1 else '')
# "1 bar"


Julia uses the dollar sign for string formatting.

foo = 3
"foo $foo" # "foo 3"


Is it possible to simply mirror the functionality of the Python code using Julia?

Answer

Yes. The $ interpolation method works with expressions in parenthesis. In this case, $bar bar$(bar != 1 ? 's' : "") is equivalent to the Python results.

As @Oxinabox mentioned, Python's inline if corresponds to Julia's ternary operator. In Julia the ternary operator a ? b : c is a handy shortcut for if a b ; else c ; end. Note this means 1==2 ? foo() : bar() does not evaluate foo().

Comments