How Does Python's .join Work?
Solution 1:
This line is there to ensure that your command is in the right syntax and has brackets and comma when you call it! I wrote it clearer in the code below:
cmd = 'insert'
arg1 = '1'
arg2 = '3'
arg3 = '10'
cmd = cmd + "(" + ",".join((arg1, arg2, arg3)) + ")"print cmd
Output:
insert(1,3,10)
Solution 2:
Consider the following input line:
insert110
So s
is the list ["insert", "1", "10"]
. Note that the list elements are all strings.
So cmd
is "insert"
and args
is ["1", "10"]
.
Now here's the part that you didn't understand. First, ",".join(args)
just creates a single string composed of the elements of arg
, separated by commas: "1,10"
.
This is then wrapped in parentheses: "(1,10)"
. Finally, it is appended to cmd
resulting in the string "insert(1,10)"
.
It then prepends "l."
to this, resulting in the string "l.insert(1,10)"
. This is then passed to eval
.
So it's invoking the insert
method on the list l
, inserting the value 10
at position 1
. I.e., it's executing l.insert(1,10)
.
Solution 3:
Your question is what does the following line mean:
cmd += "("+ ",".join(args) +")"
cmd
is a variable (with a string).
+=
is an operator which adds the right side to the left side.
"("
is a string containing a left parens.
+
is an operator that adds the left and right of itself.
",".join(args)
this makes the list, args
, into a string separated by commas. For example:
args =['bob','sue','tom'], then:
",".join(args)
> bob,sue,tom
again, +
is an operator that adds the left and right of itself.
)
is a string containing a right parens.
Thus, if args is ['bob',sue','tom], and cmd is names, then the output of this line would be:
cmd = "names"
args =["bob","sue","tom"]
cmd += "("+ ",".join(args) +")"
print cmd
> names(bob,sue,tom)
Post a Comment for "How Does Python's .join Work?"