Vin*_*ent 5 python regex string
我有以下字符串(Python):
test = " +30,0 EUR abcdefgh "
Run Code Online (Sandbox Code Playgroud)
我想删除除数字和逗号“,”以外的所有内容。
Expected result: "30.0"
Run Code Online (Sandbox Code Playgroud)
所以基于re doc我试过:
test = re.sub('^[0-9,]', "", test)
Run Code Online (Sandbox Code Playgroud)
输出是:
" +30,0 EUR abcdefgh "
Run Code Online (Sandbox Code Playgroud)
什么都没有发生。为什么?
需要^放在括号内。
>>> re.sub('[^0-9,]', "", test)
'30,0'
Run Code Online (Sandbox Code Playgroud)
要将逗号更改为小数:
>>> '30,0're.sub('[^0-9,]', "", test).replace(",", ".")
'30.0'
Run Code Online (Sandbox Code Playgroud)