python - 在字符串中的子字符串中查找值?
问题描述
我正在创建一个简单的 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()
并将其放回正确的位置。我尝试在网上查找,但这似乎是一个晦涩难懂的问题。
解决方案
您可以使用re.sub
fromre
模块在这里解决您的问题。首先,让我们定义一个简单的辅助函数,它接收一个数字字符串并计算平方根,然后返回一个字符串:
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
推荐阅读
- android - Androguard“内部”与“外部”类
- java - 文件中的内容应该如何使用协议缓冲区轻松用于进一步序列化
- woocommerce - WooCommerce 结帐状态字段映射
- powershell - 将文本文件数据转换为 csv powershell
- hyperledger-fabric - 维护应用程序级数据隐私
- laravel-7 - 如何禁用有条件的按钮
- java - 如何实现http补丁逻辑
- r - 将日期转换为自定义格式
- node.js - React Native 无法将表单数据发送到后端
- python - 即使对于非正定矩阵,Scipy Cholesky 分解也会返回 wo 错误