Hi, I'm trying to use a nested string format, with a "big" string outside and a map inside with sub-format strings for each element. Why does it not compile? Is there any idiomatic way of using such nested formatted strings?
#https://play.nim-lang.org/#ix=3rPJ
import strutils, strformat, seqUtils
var cols : seq[int]
add(cols, 1)
echo join(mapIt(cols, &"{it}"), "\n") # Works
echo &"Prefix text: {join(mapIt(cols, &"{it:20}"), "\n")}" # Error: undeclared identifier: '{}'
Hi, so from your tip I would guess I would change the outer string to a triple-quoted string: like
echo &"""Prefix text: {join(mapIt(cols, &"{it:20}"), "\n")}""" # Error: closing " expected
But I get Error: closing " expected.
I'm out of ideas so if you would point me to the proper substitution, or even cite which approach you'd take in this case it would be helpful. I'm coming from Julia and C# where string interpolations can be nested arbitrarily, I use it for structured output one-liners.
Thank you,
Yes, I just realized I can concat the strings:
import strutils, strformat, seqUtils
var cols : seq[int]
add(cols, 1)
#echo &"Prefix text: {join(mapIt(cols, &"{it:20}"), "\n")}" # Error: undeclared identifier: '{}'
echo "Prefix text: " & join(mapIt(cols, &"{it:20}"), "\n") # Works
Without any additional verbosity.
Way to go, thank you!
import strutils, strformat, seqUtils
var cols = @[1]
echo cols.mapIt(&"{it}").join("\n")
echo fmt"""Prefix text: {cols.mapIt(&"\{it\:20\}").join("\n")}"""
works on the devel branch of nim. The primary change is escaping the curly braces (which only works on devel branch)
$ nim -v
Nim Compiler Version 1.5.1 [MacOSX: amd64]
Compiled at 2021-07-03
Copyright (c) 2006-2021 by Andreas Rumpf
git hash: d1d2498c7b933b6364af450df5088aaa89b4cf4b
active boot switches: -d:release
Within parens, colons don't need to be escaped, neither does the opening curly, apparently:
echo fmt"""Prefix text: {cols.mapIt(&"{it:20\}").join("\n")}"""
should also work