使用Python正則表示式查詢字串中的所有數字
從文字中提取數字是Python資料分析中非常常見的要求。使用Python正則表示式庫可以輕鬆實現。這個庫幫助我們定義可以提取為子字串的數字模式。
示例
在下面的示例中,我們使用re模組中的findall()函式。該函式的引數是我們想要提取的模式以及我們想要從中提取的字串。請注意,下面的示例只獲取數字,而不獲取小數點或負號。
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)輸出
執行以上程式碼得到以下結果:
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '8', '4', '112']
捕獲小數點和符號
我們可以擴充套件搜尋模式,在搜尋結果中包含小數點和負號或正號。
示例
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)輸出
執行以上程式碼得到以下結果:
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '.8', '-4', '.112']
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP