Python – 從字串中提取百分比


當需要從字串中提取百分比時,可以使用正則表示式和程式包的“findall”方法。

示例

以下對其進行了說明 -

import re

my_string = 'Python is % always fun % to learn % and teach'

print("The list is : " )
print(my_string)

my_result = re.findall('\d*%', my_string)

print("The resultant list is : ")
print(my_result)

輸出

The list is :
Python is % always fun % to learn % and teach
The resultant list is :
['%', '%', '%']

說明

  • 將必需的包匯入環境。

  • 定義一個字串並將其顯示在控制檯上。

  • 使用正則表示式包的“findall”方法定義一個模式並傳遞字串以對其進行處理。

  • 這將分配給一個變數。

  • 此變數作為螢幕上的輸出顯示。

更新於: 13-Sep-2021

345 人次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告