How to extract numbers from a string in python

王林
Release: 2024-03-01 16:31:13
forward
1167 people have browsed it

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']
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!