如何在 Python 中從字串中提取子字串?
在本文中,我們將瞭解如何在 Python 中從字串中提取子字串。
第一種方法是使用正則表示式。建立搜尋模式的一串字元稱為正則表示式或正則表示式。正則表示式可用於確定字串是否包含給定的搜尋模式。
我們將使用正則表示式的re.search方法,並搜尋正則表示式給出的給定字串,然後將其提取出來。
示例 1
在下面給出的示例中,我們以字串作為輸入,並使用正則表示式 '(\$[0-9\,]*)' −提取字串的數字子字串。
import re
str1 = 'The phone is priced at $15,745.95 and has a camera.'
print("The given string is")
print(str1)
print("The numeric substring is:")
res = re.search('(\$[0-9\,]*.[0-9]{2})', str1)
if res:
print(res.group(1))
輸出
上面示例的輸出如下所示:
The given string is The phone is priced at $15,745.95 and has a camera. The numeric substring is: $15,745.95
示例 2
您可以在正則表示式中使用分組捕獲從字串中提取子字串。您需要知道要提取的子字串的格式和周圍環境。例如,如果您有一行並希望以 $xxx,xxx.xx 格式從中提取貨幣資訊,您可以使用以下內容:
import re
text = 'The phone is priced at $15,745.95 and has a camera.'
m = re.search('(\$[0-9\,]*.[0-9]{2})', text)
if m:
print (m.group(1))
輸出
這將產生以下輸出:
$15,745.95
注意 − 實際的正則表示式將取決於您的用例情況。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP