0

Given the following:

String: "{Dog} loves {Cat}",

RegExp: {([^}]+)},

Array: ["Scooby Doo", "Sylvester"]

How can I easily achieve: "Scooby Doo loves Sylvester"

4
  • Did you try anything in terms of code to solve this? Commented Jul 7, 2019 at 19:27
  • 1
    Maybe re.sub(r'{[^{}]*}', '{}', s).format(*l) (demo)? Commented Jul 7, 2019 at 19:32
  • Thank you @WiktorStribiżew it works pretty nice. Looking for the documentation to understand this beautiful "magic" ... Commented Jul 7, 2019 at 19:36
  • Got it! All you have done is replacing matches by {} and then using string replacing in python 3 style. Pretty nice trick! Commented Jul 7, 2019 at 19:41

1 Answer 1

1

You may replace each substring inside curly braces with a {} substring that acts as a placeholder when the string is passed to str.format method. The list needs to be "cast" to a sequence of variables (it is called unpacking), thus, the prefix operator * is required before the list passed to str.format.

So, the code can look like

import re
s = "{Dog} loves {Cat}"
l = ["Scooby Doo", "Sylvester"]
print(re.sub(r'{[^{}]*}', '{}', s).format(*l))
# => Scooby Doo loves Sylvester

See the Python demo.

Sign up to request clarification or add additional context in comments.

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.