user3303020
user3303020

Reputation: 1043

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

I have a file with with following strings

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

Lets say BITWIDTH = 8

I want the following output

input complex_data_8;
output complex_data_17;

How can I achieve this in python with find and replace with some mathematical operation.

Upvotes: 0

Views: 205

Answers (2)

charles
charles

Reputation: 1055

I would recommend looking into the re RegEx library for string replacement and string search, and the eval() function for performing mathematical operations on strings.

Example (assuming that there are always parentheses around what you want to evaluate) :

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"

Upvotes: 1

siulpolb
siulpolb

Reputation: 16

You can use variables for that if you know the value to change, one for the value to search and other for the new value

BITWIDTH = 8
NEW_BITWIDTH = 2 * BITWIDTH + 1

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

if you don't know the value then you need to get it first and then operate with it

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))

Upvotes: 0

Related Questions