如何在 Python 中从字符串中提取子字符串?
在本文中,我们将了解如何在 Python 中从字符串中提取子字符串。
第一种方法是使用正则表达式。创建搜索模式的一串字符称为正则表达式或正则表达式。RegEx 可用于确定字符串是否包含给定的搜索模式。
我们将使用正则表达式的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