Get only numbers from string in python

后端 未结 8 1188
感动是毒
感动是毒 2020-12-06 18:37

I want to get only the numbers from a string. For example I have something like this

just=\'Standard Price:20000\'

And I only want it to pr

相关标签:
8条回答
  • 2020-12-06 19:02

    you can use regex:

    import re
    just = 'Standard Price:20000'
    price = re.findall("\d+", just)[0]
    

    OR

    price = just.split(":")[1]
    
    0 讨论(0)
  • 2020-12-06 19:02

    If you want to keep it simpler avoiding regex, you can also try Python's built-in function filter with str.isdigit function to get the string of digits and convert the returned string to integer. This will not work for float as the decimal character is filtered out by str.isdigit.

    Python Built-in Functions Filter

    Python Built-in Types str.isdigit

    Considering the same code from the question:

    >>> just='Standard Price:20000'
    >>> price = int(filter(str.isdigit, just))
    >>> price
    20000
    >>> type(price)
    <type 'int'>
    >>>
    
    0 讨论(0)
提交回复
热议问题