I have a
JavaScript
x
2
1
string = 'long company name with technologies in it'
2
and want to replace all tokens starting with
JavaScript
1
2
1
search_string ='techno'
2
with a new token
JavaScript
1
2
1
replace_string = 'tech'.
2
I wrote a function:
JavaScript
1
11
11
1
def group_tokens(company_name, string_search, string_replace):
2
try:
3
x = company_name.split(" ")
4
print(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]")
5
exec(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]")
6
x = " ".join(x)
7
x = " ".join(re.split("s+", x, flags=re.UNICODE))
8
return(x)
9
except:
10
return np.nan
11
If I execute the lines separately it works. But the function itself doesn’t work.
JavaScript
1
2
1
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with technologies in it'
2
I’d expect
JavaScript
1
2
1
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with tech in it'
2
How can I “exec” f-string in a function?
Advertisement
Answer
You are overcomplicating this. Simply reassign x:
JavaScript
1
10
10
1
def group_tokens(company_name, string_search, string_replace):
2
try:
3
x = company_name.split(" ")
4
x = [re.sub(f'^{string_search}.*', string_replace, i) for i in x])
5
x = " ".join(x)
6
x = " ".join(re.split("s+", x, flags=re.UNICODE))
7
return x
8
except:
9
return np.nan
10
But it’s probably easier to rewrite the function similar to the following:
JavaScript
1
3
1
def group_tokens(company_name, string_search, string_replace):
2
return re.sub(f'b{string_search}S*s*', f'{string_replace} ', company_name, flags=re.UNICODE);
3