I should calculate the difference between elements two different list. This is my code :
a = ['5', '35.1', 'FFD']
b = ['8.5', '11.3', 'AMM']
difference = [each - each for each in zip(b, a)]
b-a = ['3.5','-23.8','AMM-FFD']
unsupported operand type(s) for -: 'str' and 'str'
You need to convert numbers to
floats, and if the elements cannot be converted to numbers, insert a
'-' between them.
diffs =  for i, j in zip(a, b): try: diffs.append(str(float(j) - float(i))) except ValueError: diffs.append('-'.join([j, i])) >>> print(diffs) ['3.5', '-23.8', 'AMM-FFD']
Since python is strongly typed (not to be confused with static vs. dynamic) it does not implicitly perform arithmetic on the numeric interpretation of strings if it encounters an arithmetic operator between strings. There is no obvious behavior of the minus operator with regard to strings the way there is an obvious behavior of plus (i.e., concatenate). Would you expect it to remove instances of the second string from the first string? If so, there's already a more explicit
str.replace method you can use. Or would you expect it to remove the second string from the first only if the first string ends with the second string? The expected behavior isn't 100% obvious, so the python authors did not include
__sub__ method support for strings.
operator module isn't used in your code, so no need to import it.