I know of two ways to include named arguments in a string:
name = "Mary"
pet = "lamb"
# option 1
message = "%(name)s had a little %(pet)s" % {"name": name, "pet": pet}
print(message)
# option 2
message = "{name} had a little {pet}"
message.format(name = name, pet = pet)
print(message)
# I'm not actually sure if `name = name` works, usually these are different
I don't think either of these is very readable. Is there any way to reduce the number of times I repeat variable names here?
It is important that the string arguments are named (not empty) so that:
%(name)s %(name)s quite contrary how does your %(pet)s grow?%(name)s alikuwa kidogo %(pet)sWith an object:
person.name = 'foo'
person.age = 12
You can do:
print '{name} is {age} old'.format(**person.__dict__)
With a dictionary:
a = {'name': 'foo', age: 12}
print '{name} is {age} old'.format(**a)
With a list/tuple/set/namedtuple:
a = [1,2,3]
b = (1,2,3)
c = set([1,2,3,1])
from collections import namedtuple
Foo = namedtuple('Foo', 'x y z')
foo = Foo(1,2,3)
print '{} {} {}'.format(*foo)
print '{} {} {}'.format(*a)
print '{} {} {}'.format(*b)
print '{} {} {}'.format(*c)
print '{} {} {}'.format(*foo)
However, the namedtuple is more than a tuple, it is also an object, so you can also do this:
print '{x} {z} {y}'.format(**foo._asdict())
The list could be longer, I'll stop here, but now you get an idea...
You can just have empty {} brackets in the format string. And by the way in the second one, you need to set the call to format equal to a variable as it doesn't work in-place:
message = '{} had a little {}'.format(name, pet) # < v2.7 needs numbers in brackets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With