如何从字符串中删除所有非整数字符?(Python)

4

我是一名Python初学者,有一个问题。例如,当我从文件中读取一行时,我得到了一个看起来像这样的字符串。

thestring = '000,5\r\n'

怎样从字符串中移除所有非整数字符,然后将该字符串转换为整数? 谢谢!

4
你需要能够阅读否定语、十六进制数(0xFFFFFF)或浮点数(-592.45821543e+04)吗? - AJMansfield
只是挑剔一下,但您不想删除“非整数”,而是“非数字”。 - Sebastian Negraszus
1个回答

11

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

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

使用正则表达式

>>> import re
>>> re.sub(r'[^\d]+','',strs)    #or re.sub(r'[^0-9]+','',strs)
'0005'
使用 str.joinstr.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

或者如果您需要更快的速度,可以进行翻译。 - placeybordeaux
非常感谢!现在假设我的字符串是'0005',我该如何将其反转,使其变成'5000'? - Binka
2
@Binka 使用这个:'0005'[::-1] - Ashwini Chaudhary
好奇问一下,usms有什么区别? - John
2
@johnthexiii 中的 us 表示微秒 ((10^-6)秒),而 ms 表示毫秒((10^-3)秒)。 - Ashwini Chaudhary
这个翻译的例子是否已更新为 Python 3.X? - Eliezer Miron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接