如何在Python删除括号内的文本?
在本文中,我们将学习如何在Python删除括号内的内容而不删除括号。
例子:
Input: (hai)geeks
Output: ()geeks
Input: (geeks)for(geeks)
Output: ()for()
我们可以在两种方法中删除括号内的内容而不删除括号,其中一种方法是使用 re 库中的内置方法,第二种方法是通过使用 for 循环迭代字符串来实现此功能
方法一:我们将使用re库(正则表达式)的sub()方法。
sub(): sub() 方法的功能是它会找到特定的模式并用一些字符串替换它。
此方法将查找出现在方括号或圆括号中的子字符串并将其替换为空方括号。
方法 :
- 导入 re 库
- 现在找到括号中的子字符串,并使用 sub() 方法替换为() 。
- 我们需要传递带有 2 个参数的 sub() 方法,它们是要替换的模式和字符串。
- 打印字符串。
在下面的代码中\(.*?\)表示用于查找包含某些内容的括号的正则表达式。括号()在Python中的正则表达式中具有一些特殊含义,因此使用 Backlash \来转义该含义。
Python3
# Importing module
import re
# Input string
string="(Geeks)for(Geeks)"
# \(.*?\) ==> it is a regular expression for finding
# the pattern for brackets containing some content
string=re.sub("\(.*?\)","()",string)
# Output string
print(string)
Python3
# Input string
string="geeks(for)geeks"
# resultant string
result = ''
# paren counts the number of brackets encountered
paren= 0
for ch in string:
# if the character is ( then increment the paren
# and add ( to the resultant string.
if ch == '(':
paren =paren+ 1
result = result + '('
# if the character is ) and paren is greater than 0,
# then increment the paren and
# add ) to the resultant string.
elif (ch == ')') and paren:
result = result + ')'
paren =paren- 1
# if the character neither ( nor then add it to
# resultant string.
elif not paren:
result += ch
# print the resultant string.
print(result)
输出
()for()
时间复杂度: O(2^m + n)。
其中 m 是正则表达式的大小,n 是字符串的大小。这里的 sub() 方法需要 2^m 的时间来使用正则表达式和 O(n) 来查找模式以遍历字符串并替换为“()”。
方法 2:在此方法中,我们将遍历字符串,如果要迭代的字符不在括号之间,则该字符将添加到结果字符串。
如果字符串中存在左括号或右括号,则括号将添加到结果字符串,但中间的字符串不会添加到结果字符串。
方法:
- 为字符串的每个字符迭代循环。
- 如果字符串出现'('或')' ,我们会将其添加到结果字符串。
- 如果字符串的括号编号为零,则将该字符添加到结果字符串。
- 这里如果括号数大于零,则表示正在迭代的当前字符存在于两个括号之间
- 打印结果字符串。
蟒蛇3
# Input string
string="geeks(for)geeks"
# resultant string
result = ''
# paren counts the number of brackets encountered
paren= 0
for ch in string:
# if the character is ( then increment the paren
# and add ( to the resultant string.
if ch == '(':
paren =paren+ 1
result = result + '('
# if the character is ) and paren is greater than 0,
# then increment the paren and
# add ) to the resultant string.
elif (ch == ')') and paren:
result = result + ')'
paren =paren- 1
# if the character neither ( nor then add it to
# resultant string.
elif not paren:
result += ch
# print the resultant string.
print(result)
输出
geeks()geeks
时间复杂度: O(n)。
这里 n 是字符串的长度。在代码中,我们遍历字符串并将内容附加到括号之外,因此只需要 O(n) 的时间。