我已經通過WiktorStribiżew的建議解決了這個問題。Python正則表達式點字符
已編輯:我只需要一次提取列表的第一個元素,因爲我需要對該數字執行其他操作。我在我的代碼中使用了一個循環來進行測試。
我想將算術表達式拆分爲數字列表。
例如:1 + 0.2(3^4)* 5 - > [ '1', '0.2', '3', '4', '5']
我使用重新庫在Python中,但表達式是用點符號''分割的。雖然我不包括'。'在delmiters。
即,當輸入是1 + 0.2,則輸出將是[ '1', '0', '2'],這應該是[ '1', '0.2']
的代碼是如下:
#!/bin/python
import re
delims = re.compile(r"[+-/*///^)]")
while True:
string = input()
res = list()
i = 0
while i < len(string):
if string[i] >= '0' and string[i] <= '9':
num_str = delims.split(string[i:], 1)[0]
res.append(num_str)
i += len(num_str) - 1
i += 1
print(res)
我非常感謝這個問題的任何意見!
'-'創建一個範圍,轉義或移動到char類的結尾/開始處,使用'[ - +/* ^)]' –
[Here](http://stackoverflow.com/questions/32324595/error-in-regex-to-catch-special-characters/32324646#32324646)是一個類似的問題。 –
非常感謝!你太聰明瞭! –