How can numbers be extracted from a string in Python?
A regular expression can be used to extract numbers from strings. Here is an example code:
import re
def extract_numbers(s):
pattern = re.compile(r'\d+')
numbers = re.findall(pattern, s)
return numbers
s = "abc123xyz456"
numbers = extract_numbers(s)
print(numbers) # 输出:['123', '456']
In the above example, we created a regular expression object using the re.compile() function and compiled \d+ as the pattern. \d represents matching a digit, and + represents matching one or more digits. Then, we used the re.findall() function to find all matching numbers in the string s and returned the results as a list. Finally, we printed out the extracted list of numbers.