How to extract numbers from a string in Python?

后端 未结 17 2051
星月不相逢
星月不相逢 2020-11-21 05:19

I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit() method?

Example:

17条回答
  •  再見小時候
    2020-11-21 06:00

    For phone numbers you can simply exclude all non-digit characters with \D in regex:

    import re
    
    phone_number = '(619) 459-3635'
    phone_number = re.sub(r"\D", "", phone_number)
    print(phone_number)
    

提交回复
热议问题