Get only numbers from string in python

后端 未结 8 1187
感动是毒
感动是毒 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 18:42

    A more crude way if you don't want to use regex is to make use of slicing. Please remember that this would work for extracting any number if the structure of the text remains the same.

    just = 'Standard Price:20000'
    reqChar = len(just) - len('Standard Price:')
    print(int(just[-reqChar:]))
    >> 20000
    
    0 讨论(0)
  • 2020-12-06 18:48

    You could use string.split function.

    >>> just='Standard Price:20000'
    >>> int(just.split(':')[1])
    20000
    
    0 讨论(0)
  • 2020-12-06 18:49

    You can also try:

    int(''.join(i for i in just if i.isdigit()))
    
    0 讨论(0)
  • 2020-12-06 18:51

    I think bdev TJ's answer

    price = int(filter(str.isdigit, just))
    

    will only work in Python2, for Python3 (3.7 is what I checked) use:

    price = int ( ''.join(filter(str.isdigit, just) ) )
    

    Obviously and as stated before, this approach will only yield an integer containing all the digits 0-9 in sequence from an input string, nothing more.

    0 讨论(0)
  • 2020-12-06 18:52

    You could use RegEx

    >>> import re
    >>> just='Standard Price:20000'
    >>> re.search(r'\d+',just).group()
    '20000'
    

    Ref: \d matches digits from 0 to 9

    Note: Your error

    just[0] evaluates to S as it is the 0th character. Thus S[1:] returns an empty string that is '', because the string is of length 1 and there are no other characters after length 1

    0 讨论(0)
  • 2020-12-06 18:56

    The clearest way in my opinion is using the re.sub() function:

    import re
    
    just = 'Standard Price:20000'
    only_number = re.sub('[^0-9]', '', just)
    print(only_number)
    # Result: '20000'
    
    0 讨论(0)
提交回复
热议问题