📜  Python|提取括号之间的子字符串

📅  最后修改于: 2022-05-13 01:55:39.179000             🧑  作者: Mango

Python|提取括号之间的子字符串

有时,在使用Python字符串时,我们可能会遇到需要提取某些字符之间的子字符串并且可以是括号的问题。如果我们在字符串中嵌入了元组,这可以应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用正则表达式
解决此问题的一种方法是使用正则表达式。在此我们使用合适的正则表达式并执行提取所需元素的任务。

Python3
# Python3 code to demonstrate working of
# Extract substrings between brackets
# Using regex
import re
 
# initializing string
test_str = "geeks(for)geeks is (best)"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract substrings between brackets
# Using regex
res = re.findall(r'\(.*?\)', test_str)
 
# printing result
print("The element between brackets : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract substrings between brackets
# Using list comprehension + eval() + isinstance()
 
# initializing string
test_str = "[(234, ), 4, (432, )]"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract substrings between brackets
# Using list comprehension + eval() + isinstance()
res = [str(idx) for idx in eval(test_str) if isinstance(idx, tuple)]
 
# printing result
print("The element between brackets : " + str(res))


输出 :
The original string is : geeks(for)geeks is (best)
The element between brackets : ['(for)', '(best)']


方法 #2:使用列表理解 + isinstance() + eval()
上述方法的组合也可以用来解决这个问题。在这个 eval() 中,假设括号是元组并帮助提取其中的字符串。

Python3

# Python3 code to demonstrate working of
# Extract substrings between brackets
# Using list comprehension + eval() + isinstance()
 
# initializing string
test_str = "[(234, ), 4, (432, )]"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract substrings between brackets
# Using list comprehension + eval() + isinstance()
res = [str(idx) for idx in eval(test_str) if isinstance(idx, tuple)]
 
# printing result
print("The element between brackets : " + str(res))
输出 :
The original string is : [(234, ), 4, (432, )]
The element between brackets : ['(234, )', '(432, )']