【问题标题】:How can i remove only the last bracket from a string in python?如何从 python 中的字符串中只删除最后一个括号?
【发布时间】: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


【解决方案1】:

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

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

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

模式匹配:

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

查看regex demoPython 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

【讨论】:

    【解决方案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】:

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

      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

      【讨论】:

      • hello @jbowen4 for "hell(h)o(w(orld))" 它给了我 "hell(h)o(w)" 但我想要类似 "hell(h)o "
      【解决方案4】:

      如果有用请看下面,告诉我我会进一步优化。

      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='')
      

      【讨论】:

      • 上面的代码没有给我任何输出。
      • 嘿 Rahul,你在哪里发现错误。我希望这应该有效。让我知道错误会帮助您解决问题
      猜你喜欢
      • 2022-11-19
      • 2015-06-10
      • 2015-10-05
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2011-11-18
      • 2013-09-12
      相关资源
      最近更新 更多