Andrei wrote: > Dick Moores wrote: > >> I've been trying to learn new things from the Cookbook, but here's a >> recipe the utility of which I don't understand at all. Why interpolation >> (whether the ruby way or not)? Maybe a better example than the couple >> given would help me? >> > <snip> > > Normal string formatting in Python works by including in the string a > sort of type definition (e.g. '%s' means 'insert a string here', '%d' is > 'insert an integer here', etc.). You have to supply the arguments > after the format string, in a tuple. For example: > > >>> print 'Name: %s\nAge: %d' % (username, userage) > Name: John Doe > Age: 39 > > With the recipe provided, you can put the variables you want inserted > directly in the format string - it's no longer necessary to append them > in a tuple. So for the example above, it would become: > > >>> print interp('Name: #{username}\nAge: #{userage}') > This accomplishes nearly the same thing: >>> d = {'username':'bob','userage':23} >>> print "Name: %(username)s, Age: %(userage)s" % d Name: bob, Age: 23
The only difference is that the items have to be keys in the dictionary, instead of just variables, but that's not necessarily a disadvantage. But I understand they're trying to emulate it exactly as it operates in other languages. > > The recipe has some disadvantages: > > - you have put your variable names in a string. This is bad practice - > if you rename variables, it's easy to overlook them in strings. > This is a disadvantage in the dictionary method too, it seems. > - format strings can be used to translate an application. You just give > the translator your 'Name: %s' string and he gives you 'Borkbork: %s' or > whatever. The translation doesn't need to be modified if you decide to > make a user class and get rid of the username and userage vars. > I don't see what you mean here. The string in the example, interp('Name: #{username}\nAge: #{userage}') could be translated too. > - format strings give you more control, so you can e.g. specify how many > digits a float should have when formatted. The dictionary method would allow you this control. HTH, -Luke _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor