0

I've this working code:

', '.join('%s=%r' % item for item in list)

where list is list of tuples ('key', 'value').

I want to refactore the code to use the new style string.format. I've tried it this way:

', '.join(['{!s}={!r}'.format(item) for item in list])

This results in an IndexError: tuple index out of range. Are there any better solutions than:

arguments = []
for key, value in list:
    arguments.append('{!s}={!r}'.format(key, value))

', '.join(arguments)

Context:

def __repr__(self):
    """
    This method returns a string representation of the object such that eval() can recreate the object.
    The class attributes will be ordered
    e.g. Class(attribute1='String', attribute2=3)
    """
    list =[]
    for item in vars(self).items():
        list.append(item)
    list.sort(key=lambda tup: tup[0])

    arguments = []
    for key, value in list:
        arguments.append('{!s}={!r}'.format(key, value))

    return '{!s}({!s})'.format(
        type(self).__name__,
        ', '.join(arguments)
    )
Benedikt Bock
  • 1,007
  • 15
  • 37

2 Answers2

1

Unpack your tuple.

>>> t = ('a', 'b')
>>> '{!s}={!r}'.format(*t)
"a='b'"
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

What about ', '.join(['{!s}={!r}'.format(item[0], item[1]) for item in list]) ?

Giovanni Rescia
  • 605
  • 5
  • 15