Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Replace words between double brackets in python

I can receive 2 types of strings from the user.

  1. cmd1 = inst1.exe license.dat
  2. cmd2 = {{installer}} {{license}}

And I have to replace the strings between braces with something from a dictionary ({'installer': 'inst1.exe', 'license': 'license.dat'})

I'm trying something like that:

def my_replace_method(cmd, dict)
    for key, value in dictionary.items():
        cmd.replace(key, value)

for call:

my_replace_method(cmd2, dict)

The output I got was: "{{inst1.exe}} {{license.dat}}" instead of "inst1.exe license.dat"

and

my_replace_method(cmd1, dict)

The output I got is "inst1.exe license.dat.dat" instead of "inst1.exe license.dat"

My expected output for both commands is: inst1.exe license.dat How can I write a method that works for both types of input?

question from:https://stackoverflow.com/questions/65904276/replace-words-between-double-brackets-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use cmd.replace("{{"+key+"}}", value) or cmd.replace('{{%s}}'%key, value)since using only replace replaces the text and only the text you give it.
So you need to include the braces if you want to match the braces too.

Edit:
The reasons for the two errors are as follows:

  • The braces weren't in the old strings(aka You didn't replace the braces with the new strings), so they were left behind, hence the extra braces.
  • Since your braces aren't in the old strings, Python replaces license with license.dat instead of replacing {{licence}} with license.dat.So license.dat becomes license.dat.dat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...