Another newbie question: is it possible to embed a ':' in a string literal in a fmt specification, as in:
echo fmt("{\"This is a string:\":<30})
yields
/usercode/in.nim(3, 10) Error: could not parse `"This is a string`.
/nim/lib/core/macros.nim(540, 1) Error: closing " expected
Attempting to "escape" the colon:
echo fmt("{\"This is a string\:\":<30})
yields
/usercode/in.nim(3, 31) Error: invalid character constant
How can I sneak a colon in there short of assigning the string to a variable?
Thanks!
Seems like a bug to me. This works:
let str = "This is a string:"
echo fmt("{str:<30}")
To follow myself up, this also "works", and requires only one variable definition for multiple fmt specs:
let colon = ":"
echo fmt("{\"This is a string\"}{colon:<30}{\"Another String\"}")
This is a string: Another String
Ah, I see. I'm curious though why you want to put the raw string in the curly braces. You could do:
echo fmt("This is a string{colon:<30}Another String")
There is also alignLeft() in the strutils module, but it's less attractive:
import strutils
echo "This is a string:".alignLeft(30) & "Another String"
Also, using a simple template, you could do:
import strutils
template `<`(str: string, padding: int): string =
str.alignLeft(padding)
echo "This is a string:"<30, "Another String"
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 and https://forum.nim-lang.org/t/7052#49496)