Braian Braian - 2 years ago 250
Python Question

Subtract two strings in python

I should calculate the difference between elements two different list. This is my code :

import operator
a = ['5', '35.1', 'FFD']
b = ['8.5', '11.3', 'AMM']
difference = [each[0] - each[1] for each in zip(b, a)]
print difference

I need this output:

b-a = ['3.5','-23.8','AMM-FFD']

I receive the following error:

unsupported operand type(s) for -: 'str' and 'str'

I don't want to use any class like

Answer Source

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

Also, the operator module isn't used in your code, so no need to import it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download