如何在 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]
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP