如何在Python中提取字串中的數字?


Python中有多種方法可以從字串中提取數字。一種方法是使用正則表示式。正則表示式是用於匹配和操作字串的模式。這是一個使用正則表示式從字串中提取所有數字的示例程式碼片段。

使用re.findall()函式

示例

在這個例子中,我們使用re.findall()函式搜尋文字字串中所有數字的出現。正則表示式\d+\.\d+|\d+匹配浮點數和整數。

import re
text = "The price of the book is $29.99"
numbers = re.findall('\d+\.\d+|\d+', text)
print(numbers)

輸出

['29.99']

使用isdigit()方法

另一種從字串中提取數字的方法是使用isdigit()方法,如果字串中的所有字元都是數字,則返回True。

示例

在這個例子中,我們使用split()方法將文字字串分割成一個單詞列表。然後,我們遍歷每個單詞,並使用isdigit()方法檢查它是否是數字。如果是,則將其轉換為整數後新增到numbers列表中。

text = "There are 10 apples in the basket"

numbers = []
for word in text.split():

    if word.isdigit():
        numbers.append(int(word))
print(numbers)

輸出

[10]

使用正則表示式

您可以使用Python中的re模組使用正則表示式從字串中提取數字。這是一個例子

示例

此程式碼將輸出出現在字串中的數字列表:[3, 1, 2, 3]。正則表示式'\d+'匹配字串中一個或多個數字。

import re
string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = re.findall('\d+', string)
print(numbers)

輸出

['3', '1', '2', '3']

使用迴圈和isdigit()方法

您可以迴圈遍歷字串中的每個字元,並使用isdigit()方法檢查它是否是數字。

示例

string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = []
current_number = ""

for char in string:
    if char.isdigit():
        current_number += char

    elif current_number:
        numbers.append(int(current_number))
        current_number = ""

if current_number:
    numbers.append(int(current_number))

print(numbers)

輸出

 [3, 1, 2, 3]

使用split()和isdigit()方法

如果數字由非數字字元分隔,您可以使用這些字元分割字串,然後檢查每個生成的子字串是否為數字。

示例

string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = []
for substring in string.split():
    if substring.isdigit():
        numbers.append(int(substring))
print(numbers)

輸出

[3]

使用isnumeric()方法和for迴圈

示例

此程式碼建立一個名為numbers的空列表,然後將輸入字串分割成一個單詞列表。然後,它迴圈遍歷列表中的每個單詞,並使用isnumeric()方法檢查它是否為數字。如果它是一個數字,它將被新增到numbers列表中。最後,列印numbers列表。

my_string = "I have 2 apples and 3 oranges"
numbers = []
for word in my_string.split():
    if word.isnumeric():
        numbers.append(int(word))
print(numbers)

輸出

[2, 3]

使用re.findall()函式

示例

此程式碼匯入re模組,並使用re.findall()函式查詢輸入字串中所有數字的例項。然後,使用列表推導式將生成的數字字串列表轉換為整數列表。最後,列印numbers列表。

import re
my_string = "I have 2 apples and 3 oranges"
numbers = [int(num) for num in re.findall(r'\d+', my_string)]
print(numbers)

輸出

[2, 3]

使用生成器表示式和map()函式

示例

此程式碼使用生成器表示式和map()函式建立一個整數列表。生成器表示式迴圈遍歷輸入字串中的每個單詞,並且只返回使用isdigit()方法的數字。map()函式將int()函式應用於每個數字字串,將其轉換為整數。最後,列印生成的整數列表。

my_string = "I have 2 apples and 3 oranges"
numbers = list(map(int, (word for word in my_string.split() if word.isdigit())))
print(numbers)

輸出

[2, 3]

更新於:2023年8月10日

9K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.