将成本字符串分解为整数值

时间:2012-05-17 19:23:31

标签: python string

假设我的字符串格式为$(Integer) - $(Integer)$(Integer)。什么是最简单的方法来打破这些并将它们转换为整数值?如果字符串的格式为$(Integer) - $(Integer),则取两个数字的平均值。

示例字符串:$20 - $40将转换为30(这是一个范围)

1 个答案:

答案 0 :(得分:3)

>>> string = '$20 - $40'  #'$20' will also work
>>> x = re.findall(r'\$(\d+)', string)
>>> 1. * sum(map(int, x)) / len(x)
30.0 #convert to int if you want
相关问题