当前位置:首页 > 科技动态 > 正文

如何快速的取字符串中的数字

如何快速的取字符串中的数字

要从字符串中快速提取数字,可以使用正则表达式(Regular Expression)或者字符串的内置方法。以下是一些常用的Python方法: 使用正则表达式```pyt...

要从字符串中快速提取数字,可以使用正则表达式(Regular Expression)或者字符串的内置方法。以下是一些常用的Python方法:

使用正则表达式

```python

import re

def extract_numbers(s):

return re.findall(r'd+', s)

示例

text = "The year is 2023 and the temperature is 25 degrees."

numbers = extract_numbers(text)

print(numbers) 输出: ['2023', '25']

```

使用字符串的内置方法

如果你知道字符串中数字的格式,可以使用字符串的 `isdigit()` 方法来检查每个字符是否为数字,并构建数字。

```python

def extract_numbers(s):

numbers = []

num = ''

for char in s:

if char.isdigit():

num += char

elif num:

numbers.append(int(num))

num = ''

if num:

numbers.append(int(num))

return numbers

示例

text = "The year is 2023 and the temperature is 25 degrees."

numbers = extract_numbers(text)

print(numbers) 输出: [2023, 25]

```

使用`re.sub()`方法

如果你想替换字符串中的非数字字符,可以使用`re.sub()`方法。

```python

def extract_numbers(s):

return re.sub(r'D', '', s)

示例

text = "The year is 2023 and the temperature is 25 degrees."

numbers = extract_numbers(text)

print(numbers) 输出: '202325'

```

这些方法各有优缺点,你可以根据具体需求选择合适的方法。

最新文章