简体   繁体   English

从列表中的字符串中提取数字

[英]Extract a number from a string in a list

How can I extract the prices from a list that contains for example:我如何从包含例如以下内容的列表中提取价格:

[<span class="primary-price">$61,989</span>,
 <span class="primary-price">$21,905</span>,
 <span class="primary-price">$20,595</span>]

It should give me back: prices = [61.989,21.905,20.595] or at least prices = [$61,989, $21,905, $20,595]它应该还给我:价格 = [61.989,21.905,20.595] 或至少价格 = [$61,989, $21,905, $20,595]

You can do this with regular expression (pattern matching)您可以使用正则表达式(模式匹配)来做到这一点

import re

string = '''[<span class="primary-price">$61,989</span>,
 <span class="primary-price">$21,905</span>,
 <span class="primary-price">$20,595</span>]'''

numbers = re.findall('\$(\d+,\d+)', string)

You can also replace the comma(,) and convert it to integers您还可以替换逗号 (,) 并将其转换为整数

numbers = [int(num.replace(',', '')) for num in numbers ]
print(numbers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM