如何仅从python中的字符串中删除最后一个括号?

时间:2021-07-16 17:38:36

标签: python python-3.x string python-2.7

如何只删除字符串中的最后一个括号?

例如, 输入 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

寻找其他优化的解决方案/建议..

4 个答案:

答案 0 :(得分:2)

如果有用,请看下面,让我知道我会进一步优化。

string = 'hell(h)o(world)'
count=0
r=''
for i in reversed(string):
    if count <2 and (i == ')' or i=='('):
        count+=1
        pass
    else:
        r+=i
for i in reversed(r):
    print(i, end='')

答案 1 :(得分:2)

如果您想从字符串中删除最后一个括号,即使它不在字符串的末尾,您可以尝试这样的操作。只有当您知道在字符串中某处有一个以括号开头和结尾的子字符串时,这才有效,因此您可能需要对此进行某种检查。如果您正在处理嵌套括号,您还需要进行修改。

str = "hell(h)o(world)"
r_str = str[::-1]    # creates reverse copy of string
for i in range(len(str)):
    if r_str[i] == ")":
        start = i
    elif r_str[i] == "(":
        end = i+1
        break
x = r_str[start:end][::-1]    # substring that we want to remove
str = str.replace(x,'')
print(str)

输出:

hell(h)o

如果字符串不在末尾:

str = "hell(h)o(world)blahblahblah"

输出:

hell(h)oblahblahblah

编辑:这是检测嵌套括号的修改版本。但是,请记住,如果字符串中有不平衡的括号,这将不起作用。

str = "hell(h)o(w(orld))"
r_str = str[::-1]
p_count = 0
for i in range(len(str)):
    if r_str[i] == ")":
        if p_count == 0:
            start = i
        p_count = p_count+1
    elif r_str[i] == "(":
        if p_count == 1:
            end = i+1
            break
        else:
            p_count = p_count - 1
x = r_str[start:end][::-1]
print("x:", x)
str = str.replace(x,'')
print(str)

输出:

hell(h)o

答案 2 :(得分:2)

类似的东西?

string = 'hell(h)o(w(orl)d)23'
new_str = ''
escaped = 0
for char in reversed(string):
    if escaped is not None and char == ')':
        escaped += 1

    if not escaped:
        new_str = char + new_str

    if escaped is not None and char == '(':
        escaped -= 1
        if escaped == 0:
            escaped = None

print(new_str)

这在 ) 时开始转义,并在当前级别用 ( 关闭时停止。 所以嵌套的 () 不会影响它。

答案 3 :(得分:1)

使用 re.sub('[()]', '', string) 会将字符串中的任何括号替换为空字符串。

为了匹配最后一组平衡括号,如果可以使用正则表达式PyPi module,可以使用递归模式重复第一个子组,并断言右边不再出现()

(\((?:[^()\n]++|(?1))*\))(?=[^()\n]*$)

模式匹配:

  • ( 捕获组 1
    • \( 匹配 (
    • (?:[^()\n]++|(?1))* 重复 0 次以上,匹配除 ( ) 以外的任何字符或换行符。如果这样做,请使用 (?1)
    • 递归第 1 组
    • \) 匹配 )
  • ) 关闭第 1 组
  • (?=[^()\n]*$) 正向预测,断言直到字符串末尾没有 () 或换行符

看到一个 regex demo 和一个 Python demo

例如

import regex

strings = [
    "hell(h)o(world)",
    "hel(lo(wor)ld)",
    "hell(h)o(world)blahblahblah"
]

pattern = r"(\((?:[^()]++|(?1))*\))(?=[^()]*$)"

for s in strings:
    print(regex.sub(pattern, "", s))

输出

hell(h)o
hel
hell(h)oblahblahblah
相关问题