[英]Python - extract numbers and commas from string (with re.sub)
我有以下字符串(Python):
test = " +30,0 EUR abcdefgh "
我想刪除除數字和逗號“,”之外的所有內容。
Expected result: "30.0"
所以基於re doc我試過:
test = re.sub('^[0-9,]', "", test)
輸出是:
" +30,0 EUR abcdefgh "
沒啥事兒。 為什么?
^
需要進入括號內。
>>> re.sub('[^0-9,]', "", test)
'30,0'
要將逗號更改為小數:
>>> '30,0're.sub('[^0-9,]', "", test).replace(",", ".")
'30.0'
如果你想用"."
獲得輸出"."
,你可以試試這個:
test = re.sub('[^0-9.]', "", test.replace(",","."))
test
'30.0'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.