If you’re asking how does format
work in the provided example, '{} ohm{}'.format(total, 's' * (total > 1))
, then Python is replacing {}
in the string with values provided as arguments to the format function.
In this example, total
as the first and 's'
or ''
as the second, depending on the value of total
(when operating on strings, 'string' * True == 'string'
and 'string' * False == ''
).
From Python 3.6, you can use f-strings to achieve same result:
def series_resistance(lst):
total = sum(lst)
return f"{total} ohm{'s'*(total > 1)}"