Python replace string pattern with output of function

后端 未结 4 601
臣服心动
臣服心动 2020-11-27 18:24

I have a string in Python, say The quick @red fox jumps over the @lame brown dog.

I\'m trying to replace each of the words that begin with @

4条回答
  •  清歌不尽
    2020-11-27 18:42

    Try:

    import re
    
    match = re.compile(r"@\w+")
    items = re.findall(match, string)
    for item in items:
        string = string.replace(item, my_replace(item)
    

    This will allow you to replace anything that starts with @ with whatever the output of your function is. I wasn't very clear if you need help with the function as well. Let me know if that's the case

提交回复
热议问题