Removing all non-numeric characters from string in Python

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

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

7条回答
  •  一向
    一向 (楼主)
    2020-11-29 17:57

    Many right answers but in case you want it in a float, directly, without using regex:

    x= '$123.45M'
    
    float(''.join(c for c in x if (c.isdigit() or c =='.'))
    

    123.45

    You can change the point for a comma depending on your needs.

    change for this if you know your number is an integer

    x='$1123'    
    int(''.join(c for c in x if c.isdigit())
    

    1123

提交回复
热议问题