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)
)