The following works:
from string import Template
d = { "test" : "1234" }
t = "This is a test: ${test}"
s = Template(t).safe_substitute(d)
print(s)
Output:
This is a test: 1234
However, what if I only want This is a test: 12
in the output? Can I somehow combine template string substitution and slicing?
If I change t
to "This is a test: ${test}[:2]"
it prints:
This is a test: 1234[:2]
And if I change t
to "This is a test: ${test[:2]}"
it prints:
This is a test: ${test[:2]}
I'm not sure if I can use str.format
, since both the string and the dict are loaded dynamically from files.
I cannot use f
-strings, because I need to be Python 3.4 compatible.