Python 獲取給定字串的數字字首
假設我們有一個字串,其中包含開頭處的數字。在本文中,我們將瞭解如何僅獲取字串中位於開頭的固定數字部分。
使用 isdigit
isdigit 函式判斷字串的一部分是否為數字。因此,我們將使用 itertools 中的 takewhile 函式來連線字串中每個是數字的部分。
示例
from itertools import takewhile # Given string stringA = "347Hello" print("Given string : ",stringA) # Using takewhile res = ''.join(takewhile(str.isdigit, stringA)) # printing resultant string print("Numeric Pefix from the string: \n", res)
輸出
執行以上程式碼將得到以下結果:
Given string : 347Hello Numeric Pefix from the string: 347
使用 re.sub
使用正則表示式模組 re,我們可以建立一個模式來僅搜尋數字。搜尋將僅查詢字串開頭的數字。
示例
import re # Given string stringA = "347Hello" print("Given string : ",stringA) # Using re.sub res = re.sub('\D.*', '', stringA) # printing resultant string print("Numeric Pefix from the string: \n", res)
輸出
執行以上程式碼將得到以下結果:
Given string : 347Hello Numeric Pefix from the string: 347
使用 re.findall
findall 函式的工作方式類似於 girl,只是我們使用加號而不是 *。
示例
import re # Given string stringA = "347Hello" print("Given string : ",stringA) # Using re.sub res = ''.join(re.findall('\d+',stringA)) # printing resultant string print("Numeric Pefix from the string: \n", res)
輸出
執行以上程式碼將得到以下結果:
Given string : 347Hello Numeric Pefix from the string: 347
廣告