【问题标题】:How to get the integer part only from a string in python? [duplicate]如何仅从python中的字符串中获取整数部分? [复制]
【发布时间】:2019-08-29 10:48:18
【问题描述】:

我有一个如下字符串'$123,456.12'。我想获取字符串 123456 的 rhe 值整数值。

我试过用这个功能

int(''.join(list(filter(str.isdigit, number))))

但它返回 12345612。

还有其他解决办法吗?

【问题讨论】:

  • 一个选项是int(''.join(list(filter(str.isdigit, number.split('.')[0]))))/
  • s.split('.')[0].replace('$','').replace(',','') 或 re.sub('\$|,| \.[0-9]+','',s) 也可以
  • 你也可以使用正则表达式:re.search(r'([0-9,]+)', '$123,456.12').group(1)

标签: python python-3.x


【解决方案1】:
data = '$123,456.12'

print (int(''.join(list(filter(str.isdigit, data.split('.')[0])))))
# or
print (int(''.join(i for i in data.split('.')[0] if i.isdigit())))

输出:

123456

【讨论】:

    【解决方案2】:
    x = '$123,456.12'
    end = x.index('.')
    int(x[1:end].replace(',', '')) 
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2015-07-07
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 2016-08-26
      • 2012-07-05
      相关资源
      最近更新 更多