在字符串中的小写字母序列之前插入单词 [英] Inserting a word before a sequence of lowercase letters in a string
问题描述
我正在尝试创建一个在字符串中的小写字母之前添加 Math.
的函数.
我有一个数学函数 AX + sin(B)* C + sqrt(D)
.我特意将所有变量都用大写字母表示,所以只有小写的单词是 sin
和 sqrt
.
我想让函数返回 AX + Math.sin(B)* C + Math.sqrt(D)
I have a mathematical function AX + sin(B) * C + sqrt(D)
. I have purposely put all variables in uppercase so the only lowercased words are sin
and sqrt
.
And I want the function to return AX + Math.sin(B) * C + Math.sqrt(D)
def finalString(str):
'''Returns the final string'''
for i in str:
if str[i].islower() and (not str[i - 1].islower() or i == 0):
str = str[:i] + "Math." + str[i:]
return str
但这只会使索引混乱.
有人可以帮我吗?
谢谢.
But that would only mess up the indices.
Could someone help me on this one?
Thank you.
推荐答案
我将在此处使用 re.sub
:
formula = "AX + sin(B) * C + sqrt(D)"
output = re.sub(r'([a-z]+\(.*?\))', r'Math.\1', formula)
print(formula + '\n' + output)
此打印:
AX + sin(B) * C + sqrt(D)
AX + Math.sin(B) * C + Math.sqrt(D)
请注意,我使用的正则表达式模式只会将所有小写名称的函数都匹配.这有助于避免错误的标志正匹配/替换.
Note that the regex pattern I use would only match functions with all lowercase names. This helps to avoid a false flag positive match/replacement.
这篇关于在字符串中的小写字母序列之前插入单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!