如何从列表中删除非数字字符,例如:
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
使结果如下:
['1500', '2200', '1200']
我找到了各种代码示例,但对我都没有用。
如何从列表中删除非数字字符,例如:
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
['1500', '2200', '1200']
我找到了各种代码示例,但对我都没有用。
>>> import re
>>> lst = ['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> lst
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> new_lst = [re.sub("[^0-9]", "", s) for s in lst]
>>> new_lst
['1500', '2200', '1200']
或者,您可以类似地使用str.isdigit
与str.join
,一起完成相同的任务:
>>> lst = ['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> lst
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> new_lst = [''.join(ch for ch in s if ch.isdigit()) for s in lst]
>>> new_lst
['1500', '2200', '1200']
Tokenize so that you only have the number string.
Tokenize by the comma, call the result tokens.
Set output = 0
For each token in tokens:
multiply output by 1000
parse token, call the result newnum
add newnum to output
return output
需要了解的一些函数:
编辑:哦,这是错误的 - 这将返回列表中每个值的数字值。不过,从技术上讲,你可以只返回 string(output) 作为字符串版本。
int
替换Decimal
... - Tomerikoo'\$([0-9,]*).*'
。也许您会得到 1,500 作为组结果。获取此结果后,您可以轻松地使用locale.atoi
解析数字。 - user12688644