Reputation: 1867
I'm creating a wrapper for a Minecraft Server that is supposed to take new commands from a directory called commands, which contains files named after the command, all containing the server commands used to make up that command. For example, the following snippet is from the file that defines the "tell" command:
tell <1> <sender> says: <2>
Internally, the wrapper reads the stdout of the server process, looking for indications that a user is running a command. It then splits the command up, taking from it the name "sender" which is, obviously, the person who sent the command, "command" which is a one word string indicating the command, and a list called args, which contains the arguments following the command string. For example, the syntax of the tell command is this:
tell jim hello
Which results in the following names:
sender = s0lder
command = tell
args = ['jim', 'hello']
My question is, assuming the above examples, how can I make the final string, say "output", read:
tell jim s0lder says: hello
I need a way basically, to substitute the areas surrounded by brackets in the definition string, with the corresponding names/items of the args list so that:
<sender> = sender
<1> = args[0]
<2> = args[1]
and so on for all of the items in the args list. Thanks.
Upvotes: 1
Views: 225
Reputation: 208475
Here is a solution that doesn't require you to change your format (it is all done programatically).
sender = 's0lder'
args = ['jim', 'hello']
format = "tell <1> <sender> says: <2>".replace("<", "%(<").replace(">", ">)s")
# format == 'tell %(<1>)s %(<sender>)s says: %(<2>)s'
subs = {"<sender>": sender, "<1>": args[0], "<2>": args[1]}
print format % subs
# 'tell jim s0lder says: hello'
Upvotes: 1
Reputation: 65126
If you can live with changing the format strings a little bit, the built-in format
function should be quite sufficient:
args = ["jim", "hello"]
kwargs = {"sender": "s0lder"}
print("tell {0} {sender} says: {1}".format(*args, **kwargs))
outputs
tell jim s0lder says: hello
Upvotes: 0