1

I have a string which gets replaced in the backend code. ${} indicates that the string pattern is to be replaced. Example -

I am going to ${location} for ${days}

I have a dict with values to be replaced below. I want to find if ${location} is present in the text and replace it with the key value in str_replacements. Below is my code. The string replacement does not work using .format. It works using %s but i do not want to use it.

text = "I am going to ${location} for ${days}"
str_replacements = {
    'location': 'earth',
    'days': 100,
    'vehicle': 'car',
}

for key, val in str_replacements.iteritems():
    str_to_replace = '${{}}'.format(key)
    # str_to_replace returned is ${}. I want the key to be present here.
    # For instance the value of str_to_replace needs to be ${location} so
    # that i can replace it in the text
    if str_to_replace in text:
        text = text.replace(str_to_replace, val)

I do not want to use %s to substitute the string. I want to achieve the functionality with .format function.

1
  • Can you control the format on the backend? Do you need the $s? Why not just directly use the format that .format expects? Commented Oct 7, 2020 at 6:05

3 Answers 3

2

Use an extra {}

Ex:

text = "I am going to ${location} for ${days}"
str_replacements = {
    'location': 'earth',
    'days': 100,
    'vehicle': 'car',
}

for key, val in str_replacements.items():
    str_to_replace = '${{{}}}'.format(key)
    if str_to_replace in text:
        text = text.replace(str_to_replace, str(val))
print(text)
#  -> I am going to earth for 100
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a small regular expression instead:

import re

text = "I am going to ${location} for ${days} ${leave_me_alone}"
str_replacements = {
    'location': 'earth',
    'days': 100,
    'vehicle': 'car',
}

rx = re.compile(r'\$\{([^{}]+)\}')

text = rx.sub(lambda m: str(str_replacements.get(m.group(1), m.group(0))), text)
print(text)

This would yield

I am going to earth for 100 ${leave_me_alone}

Comments

0

You can do it in two ways:

  1. Parameterised - Order of parameters is not followed strictly
  2. Non Parametrised - Order of parameters is not followed strictly

Example as follows:

enter image description here

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.