Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I express named Python string arguments more succintly?

Tags:

python

string

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:

  • they can be repeated in the string: %(name)s %(name)s quite contrary how does your %(pet)s grow?
  • they are visible when translating strings: %(name)s alikuwa kidogo %(pet)s
like image 577
lofidevops Avatar asked Jan 29 '26 21:01

lofidevops


2 Answers

With 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...

like image 58
DevLounge Avatar answered Feb 01 '26 09:02

DevLounge


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.
like image 22
anon582847382 Avatar answered Feb 01 '26 10:02

anon582847382



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!