Describes how to extract numbers from strings in Python3 and how to extract the numbers in python3.
Go to an interesting blog and see a parsing article about the ValueError: invalid literal for int () with base 10 error. The blogger has provided a solution to this error, re. sub Method
totalCount = '100abc' totalCount = re.sub("\D", "", totalCount)
However, I did not explain the meaning, so I checked other materials and made a record:
The sub function is defined in the re module of Python3.5.2 official document:
re.sub(pattern, repl, string, count=0, flags=0)
Find all substrings matching the Regular Expression pattern in string and replace them with another string repl. If no string matching pattern is found, the unmodified string is returned. Repl can be a string or a function.
Therefore, we can analyze the meaning of the preceding statement: Find a non-numeric character in the '100abc' string ('\ d' in the regular expression to indicate a non-digit) and replace it, then, only the digits are returned.
>>> totalCount = '100abc'>>> totalCount = re.sub("\D", "", totalCount)>>> print(totalCount)100>>> type(totalCount)<class 'str'>
Okay, the above explanation is complete, but what I think of is the similar problem I encountered when I crawled the Q & A that I was concerned:
Answer_num_get = soup. find ('h3 ', {'id': 'zh-question-answer-num'}) # number of answers: 32 answers if answer_num_get is not None: answer_num = int (answer_num_get.split () [0]) n = answer_num // 10
The third row can use int () because of string. split () [0] extracts the number from the answer_num_get value "32 answers" (Note: There is a space behind 32, which is very important here, because the element retrieved from zhihu is)
Split () Definition str. split (sep = None, maxsplit =-1)
>>> Import string >>> a = "32 answers" >>> B =. split () [0] >>> print (B) 32 >>> type (B) <class 'str' >>>> c = '1, 2, 3 '> c. split (',') ['1', '2', '3']> c. split (',') [0] '1'> c. split (',') [1] '2' >>>
It can be seen that the first parameter of split () is a separator. If nothing is left blank, it is separated by spaces by default.
The first method requires a regular expression, and the second method requires a separator (I guess this is the reason, there is a space after the total number of answers on the original page ). Both methods have some limitations. I don't know if there is a better way to separate numbers in strings.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.