如何使pythonic?re.search()如果結果是無
def money_from_string(s):
gold = re.search("([0-9]+)g", s)
silver = re.search("([0-9]+)s", s)
copper = re.search("([0-9]+)c", s)
s = re.sub("[0-9]+g", "", s)
s = re.sub("[0-9]+s", "", s)
s = re.sub("[0-9]+c", "", s)
assert (len(s.strip()) == 0) # should be 0
return (gold.group() or 0) * 10000 + (silver.group() or 0) * 100 + (copper.group() or 0)
這不起作用,因爲如果gold
爲None
,gold.group()
將拋出一個錯誤。
輸入例子&預期成果:
s = "15g17s5c" -> 150000 + 1700 + 5 -> 151705
s = "15g5s" -> 150000 + 500 -> 150500
s = "15g" -> 150000 -> 150000
s = "17s5c" -> 1700 + 5 -> 1705
s = "5c" -> 5 -> 5
請注意,我在輸入相應的檢查,以確保它實際上是正確的格式。 IE瀏覽器。它匹配:
MONEY_PATTERNS = [
"([0-9]+g[ ]*[0-9]+s[ ]*[0-9]+c)", # g/s/c
"([0-9]+g[ ]*[0-9]+s)", # g/s
"([0-9]+g[ ]*[0-9]+c)", # g/c
"([0-9]+s[ ]*[0-9]+c)", # s/c
"([0-9]+g)", # g
"([0-9]+s)", # s
"([0-9]+c)", # c
]
你想比檢查它是否'None'並返回不同的東西以外的東西? – khelwood
's'看起來像什麼?我可以從你的代碼猜測,但我不應該 – brianpck
我擔心它pythonic之前是正確的。 –