简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM