我是一名初级程序员,学习Python 3.4.3。我正在编写一个程序,用于标记表示数学公式的字符串,或将字符串转换为列表。其他语句与if语句一起执行
我正在使用一系列if/elif/else语句来完成此操作。我这个函数的代码如下:
def positive_or_add(usr_string, place):
""" Determines if a + or - is intended to be a add /subtract or positive
or negative. Takes a string (usr_string) and an integer (place) to
determine the place in the string. Returns true for an operator, or
negative for pos/neg
(string) -> bool
>>> '3 + 5 +(-4)
Fales
"""
#munover the place setting prior to the +/- operator
place -= 1
#munover left through the white space to determine what preceeded
while usr_string[place] == ' ':
place -= 1
if usr_string[place].isdigit() or usr_string[place] == ')':
return True
else:
return False
def tokenize(usr_string):
"""
(str) -> list
Takes a string, and tokenizes it. Basically turning the string
representing a mathimatical formual and making it into a list, eliminating
the white spaces
>>> '3 + 5 + (-4)
[3, +, 5, +, (, -4,)]
"""
token_list = []
i = 0
while i < len(usr_string):
#Add values to the list that arent white space, + or -
if usr_string[i] != ' ' and usr_string[i] != '+' and usr_string[i] != '-':
token_list.append(usr_string[i])
i += 1
elif usr_string[i] == '+' or usr_string[i] == '-':
#Determine if that + or - is an operator or pos/neg
sign = positive_or_add(usr_string, i)
if sign == True: #Operator
token_list.append(usr_string[i])
i += 1
elif sign == False: #pos/neg
token_list.append(usr_string[i] + usr_string[i + 1])
i += 2
elif usr_string == ' ':
continue
else:
print('something messed up')
i += 1
return token_list
#Test
print(tokenize('3 + 5 + (-4)'))
我的问题是,我else语句总是执行,与if/elif的语句一起。我基本上得到了'弄乱了事情'的几行,然后是我生成的列表tonek_list。
当我试图擦除else语句时,程序基本上给了我一个空行,没有任何反应。
我猜我只是没有看到这里的东西。任何帮助将不胜感激。
请在此处粘贴positive_or_add函数 –
您的输入字符串包含parens,标记器似乎无法处理p阿伦斯。 – ShadowRanger
我很抱歉,我不确定Parens是什么(还没有,我猜...) – DntMesArnd