Removing all non-numeric characters from string in Python

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

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

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 17:49

    Not sure if this is the most efficient way, but:

    >>> ''.join(c for c in "abc123def456" if c.isdigit())
    '123456'
    

    The ''.join part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only take the parts of the string that match the condition isdigit.

提交回复
热议问题