0

We are using string template to replace some values in Python String by supplying a dict . It works fine . However despite using safe_substitute this below code doesnt work as expected . Any idea why ?

from string import Template 
obj = Template("$$Tag$$") 
obj.safe_substitute({}) 

Output : '$Tag$' Expected : '$$Tag$$' 
(As there is no value to replace in the dict supplied .)

This same issue happens for '####' if I make '##' as the delimiter . Anyone knows why is it ignoring an extra delimiter ? Just trying to understand what happens under the hood .

3
  • 1
    doesnt work as expected: What would you have expected exactly? Commented Nov 20, 2013 at 19:06
  • Any reason for the down vote expect I didnt clarify the expected result ? Hope its a SO question . Commented Nov 20, 2013 at 19:08
  • Awesome guys ! I get the point , escaping thats the only way to put the real value if that is a delimiter ! Thats the detail I wanted to know . Its same as '\\' in Linux bash I think . Anyway thanks . Commented Nov 20, 2013 at 19:10

3 Answers 3

2

From docs:

$$ is an escape; it is replaced with a single $.

If you want double $, then you can use something like:

>>> obj = Template("$$$$Tag$$$$")
>>> obj.safe_substitute({})
'$$Tag$$'
>>> obj.safe_substitute({'Tag':1})
'$$Tag$$'
>>> obj = Template("$$$Tag$$$") #First $ escapes the second $
>>> obj.safe_substitute({'Tag':1})
'$1$$'
Sign up to request clarification or add additional context in comments.

Comments

1

From the doc :

"$$" is an escape; it is replaced with a single "$".

Comments

1

You have to put two dollar signs for each one that you want in the output:

>>> Template('$$$$Tag$$$$').substitute()
'$$Tag$$'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.