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

2024-04-25 18:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个文件中搜索一个特定的字符串,然后是另一个字符串。在

我有下面的绳子:

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

我想把绳子换成

^{pr2}$

所以基本上,我希望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.

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

有没有一种方法可以在不删除所有右括号的情况下完成这项任务?如果你需要更多的信息,请告诉我。在

非常感谢任何帮助。在


Tags: and字符串texthelloworldstringthatis
2条回答

您应该为此使用正则表达式,看看:https://docs.python.org/3/library/re.html,更具体地说,您需要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 \((.+?)\)"与您想要的模式匹配,然后在括号之间回复,还要注意我们capture括号之间的东西。还要注意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)

相关问题 更多 >