Python implements the function of extracting numbers from strings

You can use regular expressions or string processing functions to extract numbers from strings in Python.

Implemented using regular expressions:

import re

s = 'Hello 12345 World'
nums = re.findall(r'\d+', s)
print(nums) # ['12345']

reThe function of the module is used here findall, and the regular expression is used \d+to match the numbers in the string, and the returned result is the number in the form of a list.

Implemented using string processing functions:

s = 'Hello 12345 World'
nums = ''.join(filter(str.isdigit, s))
print(nums) # '12345'

Here, filtera function is used to filter out the numbers in the string, and then joina function is used to concatenate the numbers into a string.

Guess you like

Origin blog.csdn.net/songpeiying/article/details/132451825