I just use string{0}.format(arg) format and that solves needing to memorize % whatevers.
On Sat, Jul 23, 2011 at 11:08 AM, Martin A. Brown <mar...@linux-ip.net>wrote: > > Hello everybody, > > : > Hello! I'm having troubles understanding what is the difference > between %s > : > and %r(format characters). I did google and found something on > : > StackOverflow but I don't understand the explanation as it's not > beginner > : > orientated. > : > > : > > : > Also, I have this code from learn python the hard way. Why at line 9 > does > : > he uses %r? Why did he didn't wrote print "I said: %s." %x ? > : > > : > 1 x = "There are %d types of people." % 10 > : > 2 binary = "binary" > : > 3 do_not = "don't" > : > 4 y = "Those who know %s and those who %s." % (binary, do_not) > : > 5 > : > 6 print x > : > 7 print y > : > 8 > : > 9 print "I said: %r." % x > : > 10 print "I also said: '%s'." % y > : > 11 > : > 12 hilarious = False > : > 13 joke_evaluation = "Isn't that joke so funny?! %r" > : > 14 > : > 15 print joke_evaluation % hilarious > : > 16 > : > 17 w = "This is the left side of..." > : > 18 e = "a string with a right side." > : > 19 > : > 20 print w + e > : > > : > > : > > : > Thanks in advance! > : > : I have recently worked through that exact question myself. And > : it isn't well explained. > : > : So - the simplistic answer, gleaned (hopefully not erroneously) > : from this list: s means a string, d means a number and r can be > : either or both. y has only words, so is a string, and x has a > : number (specifically referred to as d) and words, so needs r. > > I am not horrendously well-versed here, but consider the mnemonic. > > %f float > %d digit > %s string > %r representation > > A representation is something that (might?) allow for some sort of > round-trip, later (re)construction of the object. A string is > intended for general consumption. Do you really need to distinguish > them? Only if you plan on re-consuming your own output, at which > point you should consider the representation rather than the string. > > There are doubtless more experienced hands here who will suggest > concretely what you might do, but I would suggest that you use %s > (string) for anything that you want to show to an end user and %r > iif* you are planning to (re-)consume your own printed output. > > -Martin > > * iif = if and only if > > -- > Martin A. Brown > http://linux-ip.net/ > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor