Python 中带有括号和空格的星号字符

Asterisk character in Python with parentheses and spaces

我想在文件中搜索某个字符串,该字符串后跟另一个字符串。

我有以下字符串:

string = 'Hello ) world Reply ( some text ) and some Reply ( more text ) and that is ) it.'

我想用

替换字符串
'Hello ) world some text and some more text and that is ) it.'

所以基本上,我希望 Reply 和括号消失,但我想保留括号内的任何内容,并且我想保留不跟在 Reply ( 后面的括号。我曾尝试使用 here 提供的答案,但当我尝试使用括号和空格时,它们给我带来了麻烦。我尝试使用以下代码执行此操作:

string = 'Hello world Reply ( some text ) and some Reply ( more text ) and that is it.'
find = '* Reply ( * ) *'
replace = '* * *'
for f,r in zip(find.strip('*').split('*'), replace.strip('*').split('*')):
    string = string.replace(f,r)
print string

Hello world some text and some more text and that is it.

不幸的是,这会删除所有括号。正如您所想象的,当您只想删除一对括号并且所有右括号都被删除时,嵌套括号会导致问题。

有没有办法在不删除所有右括号的情况下完成此任务?如果您需要更多信息,请告诉我。

非常感谢任何帮助。

你应该为此使用正则表达式,看看:https://docs.python.org/3/library/re.html, more specific, you want the sub 方法。

我想这就是你想要的(未经测试):

import re
string = 'Hello ) world Reply ( some text ) and some Reply ( more text ) and that is ) it.'
new_string = re.sub(r"Reply \((.+?)\)",lambda a : a.group(1), string)

试一试,告诉我!

一些解释:

sub方法的第一个参数是我们要查找和替换的模式,所以r"Reply \((.+?)\)"匹配你想要的模式,Reply后跟括号之间的东西,还要注意我们capture the thing between parenthesis. Also notice the ungreedy运算符 (?).

第二个参数是一个 lambda 函数,用于生成将要替换模式的内容,请注意它接收匹配对象作为参数。因此,我们通过返回匹配对象的第 1 组来使用捕获的数据。

第三个参数是我们要搜索和替换的字符串。

不知道这是不是你想要的:

def Reply(N):

    if N in range(0,len(Replies)):
        return Replies[N]

    Replies = ["some text", "more text"]

    string = "Hello ) world " + Reply(0) + " and some" + Reply(1) + "and that is ) it."

    print(string)