![](/img/trans.png)
[英]How do I find multiple occurences of a string in a string and return the index of its location in a space-separated list?
[英]How do I split on the space-separated math operators here?
我有一個用戶計算器,可以接受數字和用戶定義的變量。 我的計划是在以空格分隔的運算符上分割語句,例如'+':
import re
query = 'house-width + 3 - y ^ (5 * house length)'
query = re.findall('[+-/*//]|\d+|\D+', query)
print query # ['house-width + ', '3', ' - y ^ (', '5', ' * house length)']
Expecting:
['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']
使用re.split
並在分割模式周圍捕獲括號似乎很有效。 只要您在模式中具有捕獲對象,就將要拆分的模式保留在結果列表中:
re.split(' ([+-/*^]|//) ', query)
Out[6]: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']
(PS:我假設您想從您的原始正則表達式中捕獲//
整數除法運算符,您不能使用單個字符類來做到這一點,因此,作為特殊情況,我將其移出了字符類之外。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.