This question already has answers here:
Removing all non-numeric characters from string in Python
                                
                                    (6个答案)
                                
                        
                                5年前关闭。
            
                    
说我有“ 123asdf”。如何删除所有非整数字符,使其变为“ 123”?

最佳答案

你可以做:

''.join(x for x in your_string if x.isdecimal())


这将使用数字字符,并将其添加到字符串中。

例子

>>> your_string = 'asd8asdf798fad'
>>> print ''.join(x for x in your_string if x.isdecimal())
8798

>>> '1'.isdecimal()
True

>>> 'a'.isdecimal()
False

09-10 02:07