[Tutor] what %s=%s means?

Ismael Garrido ismaelgf at adinet.com.uy
Thu Jul 6 04:08:38 CEST 2006


韩宪平 wrote:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
>     """Build a connection string from a dictionary of parameters.
>
>     Returns string."""
>     return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
>
> if __name__ == "__main__":
>     myParams = {"server":"mpilgrim", \
>                 "database":"master", \
>                 "uid":"sa", \
>                 "pwd":"secret" \
>                 }
>     print buildConnectionString(myParams)
>
> Whant ";"means
> %s=%s?
> join?
>   
>>>> help(items) no matched.
>>>>         
> Where can i find stuff helpful?

"%s" % (param) is called string formatting. It builds a new string from 
a format (the first part, that looks like a regular string with %s) and 
the arguments. The idea is that the %s get replaced with the value of 
the params.

String formatting allows many complex uses (for example, format decimal 
numbers with 3 digits before the . and 2 after). If you want to learn 
more about this you should look for the python docs or some tutorial 
(Google is your Friend). Alan Gauld's tutorial is really good :) 
http://www.freenetpages.co.uk/hp/alan.gauld/ (though it seems it doesn't 
cover this particular topic).

";".method is a string method. Strings ("") are objects, and as such 
they can be called (look for Object Oriented Programming if you don't 
know what an object is). -Alan's tutorial does have this topic :) -. The 
idea is basically that you ask a string to do something (in this case, 
join the elements in the list with itself in the middle).


Ismael


More information about the Tutor mailing list