代码之家  ›  专栏  ›  技术社区  ›  moltarze

在字符串中的子字符串中查找值?

  •  2
  • moltarze  · 技术社区  · 8 年前

    我正在创建一个简单的python计算器,它使用操作顺序来进行简单的数学运算,并添加平方根和整数除法特性。其概念是,用户可以将其希望的平方根值括在 sqr() 功能(例如, sqr(25) 等于5)。

    问题是,我很难从公式字符串中提取这个值。下面是它应该做什么的伪代码:

    b = 'sqr(25)+5*3' # equation
    
    # My pseudo-code:
    # 1. Identify use of sqr()
    # 2. Pull 'sqr(25)' out to be solved
    # 3. Pull value (25) out and solve it with math.sqrt()
    # 4. Replace 'sqr(25)' with the solved value (5)
    # 
    # b should now be equal to:
    #   '5+5*3'
    

    我很难从 Sqr() 把它放回正确的位置。我试着上网,但这似乎是一个更模糊的问题。

    2 回复  |  直到 7 年前
        1
  •  2
  •   user3483203    8 年前

    你可以用 re.sub re 模块来解决您的问题。首先,让我们定义一个简单的helper函数,它接受一个数字字符串并计算平方根,然后返回一个字符串:

    def str_2_sqrt(s):
        return str(math.sqrt(int(s)))
    

    现在对于困难的部分,我们将使用 回复:SUB ,使用自定义lambda函数调用 str_2_sqrt 并将结果放回字符串中:

    >>> re.sub(r'sqr\((\d+)\)', lambda x: str_2_sqrt(x.group(1)), b)
    5.0+5*3
    
        2
  •  0
  •   U13-Forward    8 年前
    b = 'sqr(25)+5*3' # equation
    import math
    def f(s):
       s1=s.replace('sqr','')
       s2=s1.replace(s1.split(')')[0][1:],str(int(math.sqrt(int(s1.split(')')[0][1:])))))
       return s2.replace(')','').replace('(','')
    print(f(b))