top | item 7152562

(no title)

drewblay | 12 years ago

>pets = ['Dog', 'Cat', 'Hamster']

>for pet in pets:

> print('A', pet, 'can be very cute!')

This may be nit picking but I prefer output like this:

print 'A %s can be very cute!' %(pet)

discuss

order

macbony|12 years ago

I prefer

  print("A {0} can be very cute!".format(pet))
.format() is very versatile.

  d = {'first': 'Robert', 'last': 'Paulson'}
  print("His name was {first} {last}!".format(**d))
  >> His name was Robert Paulson!


  class Person:
      def __init__(self, first, last):
          self.first, self.last = first, last

  p = Person('Robert', 'Paulson')
  print("His name is {0.first} {0.last}!".format(p))
  >> His name was Robert Paulson!
You also do not need to know what type is being passed in as the __str__ method is used for .format().

rsfinn|12 years ago

Possibly because you haven't moved to Python 3?

pekk|12 years ago

Python 3 doesn't dictate that style, just the parentheses