siteshen
2018-04-26 01:44:28 +08:00
# -*- coding: utf-8 -*-
# 不是很清楚你的需求,写了个函数收集字符串中的连续数字和连续符号,供参考。
def collect(string):
operands = []
operators = []
last_symbol = ''
is_last_digit = False
for s in string:
if is_last_digit:
if s.isdigit():
# both are digist, append
last_symbol += s
else:
# digist and not digist, end scaning
operands.append(last_symbol)
last_symbol = s
else:
if not s.isdigit():
# both are not digist, append
last_symbol += s
else:
# digist and not digist, end scaning
operators.append(last_symbol)
last_symbol = s
is_last_digit = s.isdigit()
# append last symbol
if is_last_digit:
operands.append(last_symbol)
else:
operators.append(last_symbol)
return operands, operators
if __name__ == '__main__':
print(collect('(40+26*55)-1102-11'))
print(collect('40+26*55-1102-11'))
# `for` 和 `# appending last symbol` 后的 `if` 一个缩进层级,其他的缩进层级应该不需要额外的说明。
# 输出结果如下(本地没 python3 )
# (['40', '26', '55', '1102', '11'], ['(', '+', '*', ')-', '-'])
# (['40', '26', '55', '1102', '11'], ['', '+', '*', '-', '-'])