如何在字符串中找到最左边的数字和/或运算符。该字符串是一个算术表达式。 [英] How do I find the leftmost number and/or operator in a string. The string is an arithmetic expression.
本文介绍了如何在字符串中找到最左边的数字和/或运算符。该字符串是一个算术表达式。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设一个字符串是1 + 2-3 / 4 * 5
如果我将该位置设为2.那么如何返回最左边数字的值2和 - 最左边的运营商
我尝试了什么:
我发现了对于运营商。但是我需要字符串的帮助。
Suppose a string is "1+2-3/4*5"
If I give the position as 2. Then how do I return the value 2 for the leftmost number and - for the leftmost operator
What I have tried:
I have found out for operator. But I need help for string.
op=['+','-','*','/']
for i in range(len(txt)):
if txt[i] in op:
return(i)
break
else:
return(-1)
推荐答案
您需要将字符串解析为标记,数字和运算符,然后根据结果进行计算。请参阅字符串以润色表示法 - Google搜索 [ ^ ]
You need to parse the string into tokens, numbers and operators and then do the calculations from the results. See string to polish notation - Google Search[^]
这篇关于如何在字符串中找到最左边的数字和/或运算符。该字符串是一个算术表达式。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文