如何在Python中從字串中獲取整數值?
在本文中,我們將瞭解如何在Python中從字串中獲取整數值。
第一種方法是使用filter()方法。我們將字串和isdigit()方法傳遞給filter方法。Python有一個內建函式叫做filter()。像列表或字典這樣的可迭代物件可以應用filter函式來建立一個新的迭代器。根據您提供的條件,這個新的迭代器可以很好地過濾掉特定的元素。
filter()方法檢查字串中的數字,並過濾掉滿足isdigit()條件的字元。我們需要將結果輸出轉換為int才能獲得整數輸出。
示例
在下面的示例中,我們以字串作為輸入,並使用filter()和isdigit()方法查詢字串中存在的整數−
str1 = "There are 20 teams competing in the Premier League"
print("The given string is")
print(str1)
print("The number present in the string is")
print(int(filter(str.isdigit(), str1)))
輸出
上面示例的輸出如下所示:
The given string is There are 20 teams competing in the Premier League The number present in the string is 20
使用正則表示式
第二種方法使用正則表示式。要使用它,請匯入re庫,如果尚未安裝,則安裝它。匯入re庫後,我們可以使用正則表示式“\d+”來識別數字。字串和正則表示式“\d+”將作為輸入傳送到re.findall()函式,該函式將返回提供的字串中包含的所有數字的列表。
示例
在下面的示例中,我們以字串作為輸入,並使用正則表示式查詢字串中存在的整數。
import re
str1 = "There are 21 oranges, 13 apples and 18 Bananas in the basket"
print("The given string is")
print(str1)
print("The number present in the string is")
print(list(map(int, re.findall('\d+', str1))))
輸出
上面示例的輸出如下所示:
The given string is There are 21 oranges, 13 apples and 18 Bananas in the basket The number present in the string is [21, 13, 18]
使用split()方法
第三種方法是使用split()、append()和isdigit()方法。首先,我們將使用split()方法在空格處分割字串,然後我們將使用isdigit()方法檢查每個元素是否為數字,如果元素是數字,則使用append()方法將其新增到新列表中。
示例
在下面的示例中,我們以字串作為輸入,並使用split()方法查詢字串中存在的數字−
str1 = "There are 21 oranges, 13 apples and 18 Bananas in the basket"
print("The given string is")
print(str1)
print("The number present in the string is")
res = []
for i in str1.split():
if i.isdigit():
res.append(i)
print(res)
輸出
上面示例的輸出如下所示:
The given string is There are 21 oranges, 13 apples and 18 Bananas in the basket The number present in the string is ['21', '13', '18']
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP