对字符串执行数学运算后如何查找和替换

How to I find and replace after performing math on the string

我有一个包含以下字符串的文件

input complex_data_BITWIDTH;
output complex_data_(2*BITWIDTH+1);

假设 BITWIDTH = 8

我想要以下输出

input complex_data_8;
output complex_data_17;

如何在 python 中通过查找和替换某些数学运算来实现这一点。

我建议查看用于字符串替换和字符串搜索的 re RegEx 库,以及用于对字符串执行数学运算的 eval() 函数。

示例(假设您要评估的内容始终有括号):

import re

BITWIDTH_VAL = 8
string_initial = "something_(BITWIDTH+3)"

string_with_replacement = re.sub("BITWIDTH", str(BITWIDTH_VAL), string_initial) 
# note: string_with_replacement is "something_(8+3)"

expression = re.search("(\(.*\))", string_with_replacement).group(1)
# note: expression is "(8+3)"

string_evaluated = string_with_replacement.replace(expression, str(eval(expression)))
# note: string_evaluated is "something_11"

如果您知道要更改的值,则可以为此使用变量,一个用于要搜索的值,另一个用于新值

BITWIDTH = 8
NEW_BITWIDTH = 2 * BITWIDTH + 1

string_input = 'complex_data_8;'
string_output = string_input.replace(str(BITWIDTH), str(NEW_BITWIDTH))

如果您不知道该值,则需要先获取它,然后再对其进行操作

string_input = 'complex_data_8;'
bitwidth = string_input.split('_')[-1].replace(';', '')
new_bitwidth = 2 * int(bitwidth) + 1
string_output = string_input.replace(bitwidth, str(new_bitwidth))

试试这个,我不知道是否有任何捷径,但我认为它有效

A="complex_data_13"
no1='0'
st1=''
for x in A:
    if x.isdigit()==True:
        no1+=x
    else:
        st1+=x
calc =2*int(no1)+1
print(st1+str(calc))