Strip all non-numeric characters (except for “.”) from a string in Python

后端 未结 6 1519
死守一世寂寞
死守一世寂寞 2020-12-07 22:26

I\'ve got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:

val = \'\'.join([c for c in val          


        
6条回答
  •  没有蜡笔的小新
    2020-12-07 22:59

    You can use a regular expression (using the re module) to accomplish the same thing. The example below matches runs of [^\d.] (any character that's not a decimal digit or a period) and replaces them with the empty string. Note that if the pattern is compiled with the UNICODE flag the resulting string could still include non-ASCII numbers. Also, the result after removing "non-numeric" characters is not necessarily a valid number.

    >>> import re
    >>> non_decimal = re.compile(r'[^\d.]+')
    >>> non_decimal.sub('', '12.34fe4e')
    '12.344'
    

提交回复
热议问题