![](/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.