我有这个字符串:a9 * a9 + a10 * a10 我希望:a9 * a8 + a10 * a9
我认为来自Python的re.sub()应该是有用的,但我不熟悉我在一些例子中看到的group()。任何帮助将不胜感激。
答案 0 :(得分:1)
这是另一种解决方法:
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
答案 1 :(得分:0)
假设输入结构为a\d*a\d + a\d*a\d + ...
,您可以在re.sub
函数中使用回调:
import re
def decrement(match):
if match.group(1) != match.group(2):
return match.group(0)
return 'a{}*a{}'.format(match.group(1), str(int(match.group(2)) - 1))
re.sub(r'a(\d)\*a(\d)', decrement, 'a3*a3 + a5*a5 + a3*a7')
# a3*a2 + a5*a4 + a3*a7