【发布时间】:2021-09-25 12:07:06
【问题描述】:
如何只删除字符串中的最后一个括号?
例如, 输入 1:
"hell(h)o(world)"
我想要这个结果:
"hell(h)o"
输入 2:-
hel(lo(wor)ld)
我想要:-
hel
如您所见,中间的括号保持不变,只有最后一个括号被移除。
我试过了:-
import re
string = 'hell(h)o(world)'
print(re.sub('[()]', '', string))
输出:-
hellhoworld
我想出了一个解决方案:-
我是这样做的
string = 'hell(h)o(world)'
if (string[-1] == ")"):
add=int(string.rfind('(', 0))
print(string[:add])
输出:-
hell(h)o
寻找其他优化的解决方案/建议..
【问题讨论】:
-
请澄清您的问题。您上面的代码似乎旨在删除括号或括号。您还声明要移除匹配的左侧外壳。你想用嵌套的外壳做什么,例如
hel(lo(wor)ld)?正如其他人所指出的那样,将您的尝试作为答案发布是不合适的,尤其是当您发现它不令人满意时。 -
@Prune 感谢上述评论,如果是“hel(lo(wor)ld)”,它将是“hel”,因为我想删除最后一个嵌套的括号。
-
这个“hell(h)o(world)blahblahblah”怎么样,你的输出是什么?
-
@Hamzawi 在“hell(h)o(world)blahblahblah”的情况下将是“hell(h)oblahblahblah”
-
您的代码在此示例中失败并返回 "hel(lo" ,对吗?
标签: python python-3.x string python-2.7