如何在Python函数中执行f-string?字符串替换函数失效问题
问题描述
现有字符串:
string = 'long company name with technologies in it'
需要将所有以search_string = 'techno'开头的单词(token)替换为replace_string = 'tech'。
编写了如下函数:
def group_tokens(company_name, string_search, string_replace): try: x = company_name.split(" ") print(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]") exec(f"x = [re.sub('^{string_search}.*', '{string_replace}', i) for i in x]") x = " ".join(x) x = " ".join(re.split("\\s+", x, flags=re.UNICODE)) return(x) except: return np.nan
单独执行代码行时可正常工作,但调用函数后未实现预期替换:
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with technologies in it'
预期输出应为:
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with tech in it'
问题原因与解决方法
问题出在不必要地使用exec和f-string拼接代码字符串,这种做法不仅容易引发作用域或字符串转义问题,而且完全没有必要。直接在函数内编写列表推导式即可实现需求,无需将代码转为字符串执行。
修正后的函数(需提前导入re和numpy):
import re import numpy as np def group_tokens(company_name, string_search, string_replace): try: # 将字符串分割为单词列表 tokens = company_name.split(" ") # 遍历每个单词,替换以指定前缀开头的内容 replaced_tokens = [re.sub(f'^{string_search}.*', string_replace, token) for token in tokens] # 拼接回字符串并清理多余空格 cleaned_str = " ".join(replaced_tokens) cleaned_str = " ".join(re.split("\\s+", cleaned_str, flags=re.UNICODE)) return cleaned_str except: return np.nan
测试调用:
result = group_tokens('long company name with technologies in it', 'techno', 'tech') print(result) # 输出:long company name with tech in it
补充说明
原代码中exec的问题在于:虽然生成的代码字符串逻辑正确,但exec在函数局部作用域中执行时,变量赋值可能无法正确覆盖外部的x(具体取决于Python的作用域规则),而且这种写法既不直观也不利于维护。直接使用列表推导式是更简洁、可靠的实现方式。
内容的提问来源于stack exchange,提问作者Judy
相关产品推荐
相关产品推荐

