【问题标题】:How to remove all non-integers from a string? (Python)如何从字符串中删除所有非整数? (Python)
【发布时间】:2013-06-18 20:15:20
【问题描述】:

我对 python 很陌生。我有个问题。例如,当我从文件中读取一行时,我有一个看起来像这样的字符串。

thestring = '000,5\r\n'

如何从该字符串中删除所有非整数,然后将该字符串转换为整数本身?谢谢!

【问题讨论】:

  • 您需要能够读取负数、十六进制 (0xFFFFFF) 还是浮点数 (-592.45821543e+04)?
  • 只是吹毛求疵,但你不想删除非整数,而是非数字

标签: python regex string


【解决方案1】:

使用str.translate,这可能是最快的方法:

>>> strs = '000,5\r\n'    
>>> from string import ascii_letters, punctuation, whitespace
>>> ignore = ascii_letters + punctuation + whitespace
>>> strs.translate(None, ignore)
'0005'

使用regex:

>>> import re
>>> re.sub(r'[^\d]+','',strs)    #or re.sub(r'[^0-9]+','',strs)
'0005'

使用str.join 和str.isdigit:

>>> "".join([x for x in strs  if x.isdigit()])
'0005'

使用int()获取整数:

>>> int('0005')
5

时间比较:

>>> strs = strs*10**4
>>> %timeit strs.translate(None, ignore)
1000 loops, best of 3: 441 us per loop

>>> %timeit re.sub(r'[^\d]+','',strs)
10 loops, best of 3: 20.3 ms per loop

>>> %timeit re.sub(r'[^0-9]+','',strs)
100 loops, best of 3: 17.1 ms per loop

>>> %timeit "".join([x for x in strs  if x.isdigit()])
10 loops, best of 3: 19.2 ms per loop

【讨论】:

  • 如果您需要稍微快一点的东西,也可以翻译一下。
  • 非常感谢!现在假设我的字符串是 '0005' 我怎样才能反转我的字符串以便它现在读取 '5000' ?
  • @Binka 使用这个:'0005'[::-1]
  • 出于好奇,us 和 ms 有什么区别?
  • @johnthexiii us 是 microsecond ((10^-6)sec) 和 ms 是 millisecond((10^-3)sec)。
猜你喜欢
  • 2011-10-19
  • 2010-11-17
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 2013-11-12
  • 2010-12-04
相关资源
最近更新 更多