Removing all non-numeric characters from string in Python

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

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

7条回答
  •  有刺的猬
    2020-11-29 18:02

    Just to add another option to the mix, there are several useful constants within the string module. While more useful in other cases, they can be used here.

    >>> from string import digits
    >>> ''.join(c for c in "abc123def456" if c in digits)
    '123456'
    

    There are several constants in the module, including:

    • ascii_letters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
    • hexdigits (0123456789abcdefABCDEF)

    If you are using these constants heavily, it can be worthwhile to covert them to a frozenset. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.

    >>> digits = frozenset(digits)
    >>> ''.join(c for c in "abc123def456" if c in digits)
    '123456'
    

提交回复
热议问题