我想从字符串对象中提取子字符串。我要提取的文字是价格数据,最后是€。价格可以是3位数或4位数。
text = "xxxxxx; AAAA€; xxxxxxx"
要么
text = "xxxxxx; AAA€; xxxxxxx"
我的代码:
position = text.find("€")
price_to_clean = text[(position - 4):(position - 1)]
price = price_to_clean.rpartition(";")[-1]
我的想法是搜索到€,然后反向提取4位数(子串将是“AAAA”或“; AAA€”)。然后从后一个分号中删除分号。我想知道是否有更好的方法来实现这一目标。例如。找到€然后反向搜索直到分号?
使用正则表达式。 re.search
例如:
import re
text = "xxxxxx; 1000€; xxxxxxx"
m = re.search("(?P<price>\d+€)", text)
if m:
print(m.group('price'))
输出:
1000€