首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数执行f-string

函数执行f-string
EN

Stack Overflow用户
提问于 2022-09-24 17:53:11
回答 3查看 60关注 0票数 0

我有一个

代码语言:javascript
复制
string = 'long company name with technologies in it'

并希望替换所有以

代码语言:javascript
复制
search_string ='techno'

带着新的记号

代码语言:javascript
复制
replace_string = 'tech'.

我写了一个函数:

代码语言:javascript
复制
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

如果我单独执行这些行,它就能工作。但是这个函数本身不起作用。

代码语言:javascript
复制
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with technologies in it'

我以为

代码语言:javascript
复制
group_tokens('long company name with technologies in it', 'techno', 'tech') = 'long company name with tech in it'

如何在函数中“执行”f-字符串?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-09-24 17:59:02

你把事情搞得太复杂了。只需重新分配x:

代码语言:javascript
复制
def group_tokens(company_name, string_search, string_replace):   
  try:
    x = company_name.split(" ") 
    x = [re.sub(f'^{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

但是,重写类似于以下内容的函数可能更容易一些:

代码语言:javascript
复制
def group_tokens(company_name, string_search, string_replace):   
  return re.sub(f'\b{string_search}\S*\s*', f'{string_replace} ', company_name, flags=re.UNICODE);
票数 2
EN

Stack Overflow用户

发布于 2022-09-24 18:03:39

代码语言:javascript
复制
def replace(string,x,y):
    words = string.split(' ')
    string = ''
    while words:
        word = words.pop(0)
        if word.startswith(x):
            word = y
        string+=word+' '
    return string[:-1]

print(replace('long company name with technologies in it', 'techno', 'tech'))
票数 0
EN

Stack Overflow用户

发布于 2022-09-24 18:08:13

我肯定把事情复杂化了。谢谢:-)

代码语言:javascript
复制
def group_tokens(company_name, string_search, string_replace):   
  try:
    x = company_name.split(" ") 
    x = [re.sub(f'^{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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73839421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档