Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
2Cubed Avatar asked Apr 06 '26 18:04

2Cubed


1 Answers

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().

like image 107
Dan Getz Avatar answered Apr 08 '26 08:04

Dan Getz