我有这个字符串:a9 * a9 + a10 * a10
我想拥有:a9 * a8 + a10 * a9

我认为Python的re.sub()应该有用,但是我对在某些示例中看到的group()并不熟悉。任何帮助,将不胜感激。

最佳答案

这是另一种解决方法:

import re

s = 'a9*a9 + a10*a10 + a8*a8 + a255*a255 + b58*b58 + c58*c58'
string = re.sub('[ ]', '', s)  # removed whitespace from string (optional:only if you are not sure how many space you can get in string)
x = string.split('+')
pattern = re.compile(r'([a-z])([\d]+)')
ans = ''
for element in x:
    for letter, num in re.findall(pattern, element):
        st = ''
        for i in range(len(element.split('*'))):
            st = st + '*' + (letter+str(int(num)-i))
            # print(str(letter) + str(int(num)-i))
    ans = ans + '+' + st[1:]
print(ans[1:])


输出:

a9*a8+a10*a9+a8*a7+a255*a254+b58*b57+c58*c57

关于python - 用减量仅替换一些数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44213305/

10-13 03:09