Removing all non-numeric characters from string in Python

后端 未结 7 1092
遥遥无期
遥遥无期 2020-11-29 17:42

How do we remove all non-numeric characters from a string in Python?

7条回答
  •  不知归路
    2020-11-29 18:01

    This should work for both strings and unicode objects in Python2, and both strings and bytes in Python3:

    # python <3.0
    def only_numerics(seq):
        return filter(type(seq).isdigit, seq)
    
    # python ≥3.0
    def only_numerics(seq):
        seq_type= type(seq)
        return seq_type().join(filter(seq_type.isdigit, seq))
    

提交回复
热议问题