如何在 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']

更新於: 2022年12月7日

11K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.