| string interpolation
|
name = "Fufu"
age = 2
print(f"{name} is {age} years old.")
|
import std/strformat # &"Hello {name}!"
let
name = "Fufu"
age = 2
echo &"{name} is {age} years old."
echo fmt"{name} is {age} years old." # same thing as &"..."
|
Output:
&"…" and fmt"…" are very similar but they are not exactly the same. The difference is explained in the docs. I suggest using &"…".
Using a format specifier
| format spec
|
import math
pi = math.pi
print(pi) # 3.141592653589793
print(f"short: {pi:.2f}") # short: 3.14
|
import std/strformat # &"Hello {name}!"
import std/math # PI
echo PI # 3.141592653589793
echo &"short: {PI:.2f}" # short: 3.14
|
Using a template string
| filling a template string
|
template = "{0} is {1} years old."
# Fufu is 2 years old.
print(template.format("Fufu", 2))
|
import std/strutils # !!! not std/strformat
let templ = "$1 is $2 years old."
# Fufu is 2 years old.
echo templ.format("Fufu", 2) # new style
# Fufu is 2 years old.
echo templ % ["Fufu", "2"] # old style; "2" is a string too
|
Pay attention that template is a keyword in Nim, hence the templ variable name.
The thing ["Fufu", "2"] is an array, and all its elements must have the same type. Here, every element must be a string. Don't forget that the `$` operator that can convert anything to a string.
However, it's simpler to use the .format() "method". There, the arguments can have various types. Another example for this:
import std/strutils
let code = 200
echo "HTTP code: $1".format(code) # HTTP code: 200
Exercise