Home > Article > Backend Development > How to extract numbers from a string in python
You can use regular expressions to extract numbers in strings.
import re def extract_numbers(string): numbers = re.findall(r'\d+', string) return numbers # 示例 string = 'Hello 123 World 456' numbers = extract_numbers(string) print(numbers) # 输出: ['123', '456']
In the above code, the re.findall()
function uses the regular expression r'\d '
to match numbers in the string. \d
means matching a numeric character,
means matching one or more consecutive numeric characters. re.findall()
The function will return all matching results, that is, a list of numbers in the string.
The above is the detailed content of How to extract numbers from a string in python. For more information, please follow other related articles on the PHP Chinese website!