溫馨提示×

Python怎么從一個字符串中提取數字

小億
208
2024-05-27 16:37:07
欄目: 編程語言

有多種方法可以從一個字符串中提取數字,以下是其中一種方法:

  1. 使用正則表達式:
import re

s = "There are 123 numbers in this string"
numbers = re.findall(r'\d+', s)

for number in numbers:
    print(number)

這段代碼使用re.findall函數來查找字符串中的所有連續(xù)數字序列,并將它們存儲在一個列表中。然后可以遍歷這個列表,處理或輸出找到的數字序列。

  1. 使用列表解析:
s = "There are 123 numbers in this string"
numbers = [int(num) for num in s if num.isdigit()]

for number in numbers:
    print(number)

這段代碼使用列表解析來遍歷字符串中的每個字符,如果字符是數字,則將其轉換為整數并添加到列表中??梢愿鶕枰M行進一步處理或輸出。

0