In the python interpreter I enter the following code:
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secre
t"}
print "&".join("%s_%s" % (i,y) for i,y in params.items())
And, understandably, I get the following output:
pwd_secret&database_master&uid_sa&server_mpilgrim
But when I run the the following code:
for i,y in params.items():
print "&".join("%s_%s" % (i,y))
I get this strange output:
p&w&d&_&s&e&c&r&e&t
d&a&t&a&b&a&s&e&_&m&a&s&t&e&r
u&i&d&_&s&a
s&e&r&v&e&r&_&m&p&i&l&g&r&i&m
Both code blocks seem to do the same thing. Why is the output different?
In the first case, you are using a generator expression to create a sequence of strings like ‘pwd_secret’, between which are interpolated ‘&’.
In the second case, you are calling join on each string like
'pwd_secret'; strings are a type of sequence, so join does what it does, which is place the separator between each element of the sequence passed to it.