在python中减去两个字符串 [英] Subtract two strings in python

查看:261
本文介绍了在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

我需要以下输出:

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

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

我收到以下错误:

--'str'和'str'的不受支持的操作数类型

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

我不想使用numpypandas

I don't want to use any class like numpy or pandas

推荐答案

您需要将数字转换为float,如果元素不能转换为数字,请在它们之间插入'-'.

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']

由于python是 strong 类型的输入(不要与 static dynamic 混淆),因此它不会隐式地对数字解释执行算术运算如果在字符串之间遇到算术运算符,则为字符串.负运算符对于字符串没有 obvious 行为,就像存在明显的plus行为(即串联)一样.您是否希望它从第一个字符串中删除第二个字符串的实例?如果是这样,您已经可以使用更明确的str.replace方法.还是仅当第一个字符串以第二个字符串结尾时,您才希望它从第一个字符串中删除第二个字符串?预期的行为并非100%明显,因此python作者并未包含对字符串的__sub__方法支持.

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模块,因此无需导入.

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

这篇关于在python中减去两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆