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

时间:2018-07-13 23:54:40

标签: python string replace substring math.sqrt

我正在创建一个简单的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 个答案:

答案 0 :(得分:2)

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

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

现在最困难的部分是,我们将使用 re.sub ,以及一个自定义lambda函数,该函数调用 str_2_sqrt 并将结果放入返回字符串:

>>> re.sub(r'sqr\((\d+)\)', lambda x: str_2_sqrt(x.group(1)), b)
5.0+5*3

答案 1 :(得分:0)

with open('fixed.json') as f:
    contents = f.read()
decoder = json.JSONDecoder()
while contents:
    data, idx = decoder.raw_decode(contents)
    do_stuff(data)
    contents = contents[idx:].lstrip()
相关问题