Python 2.7 在python中从多组括号之间的字符串中提取文本

Python 2.7 在python中从多组括号之间的字符串中提取文本,python-2.7,Python 2.7,如果字符串=Firstname Lastname(email1@place.edu)Firstname2 Lastname2(email2@place.edu) 我想创建一个新的字符串email1@place.edu,email2@place.edu 我试过了 string= string.partition('(')[-1].partition(')')[0] 但是我得到了email1@place.edu)Firstname2 Lastname2(email2@place.edu 我怎样才能

如果字符串=
Firstname Lastname(email1@place.edu)Firstname2 Lastname2(email2@place.edu)
我想创建一个新的字符串
email1@place.edu,email2@place.edu

我试过了

string= string.partition('(')[-1].partition(')')[0]
但是我得到了
email1@place.edu)Firstname2 Lastname2(email2@place.edu

我怎样才能分开这根绳子

string.split()
您可以通过传递一个参数来告诉Python您想要使用的
split()

split()

在向SO发布(特定)问题之前,您应该始终检查google和文档,以便获得最佳反馈

编辑:

如果您只是试图访问带括号的字符串,那么可以使用正则表达式或python的


使用正则表达式

import re 
regexp_pattern = '\([^\(\r\n]*\)'
st = "Firstname Lastname (email1@place.edu) Firstname2 Lastname2 (email2@place.edu)"
a = re.findall(regexp_pattern, st) #this gives you the list ['(email1@place.edu)','(email2@place.edu)']
b = ''.join(a)[1:-1] #this gives you the string 'email1@place.edu)(email2@place.edu'
b.replace(")(", ",") #this gives you the string 'email1@place.edu,email2@place.edu'
当然,如果你更喜欢,你可以做得更短(我喜欢):

import re 
regexp_pattern = '\([^\(\r\n]*\)'
st = "Firstname Lastname (email1@place.edu) Firstname2 Lastname2 (email2@place.edu)"
a = re.findall(regexp_pattern, st) #this gives you the list ['(email1@place.edu)','(email2@place.edu)']
b = ''.join(a)[1:-1] #this gives you the string 'email1@place.edu)(email2@place.edu'
b.replace(")(", ",") #this gives you the string 'email1@place.edu,email2@place.edu'
import re 
regexp_pattern = '\([^\(\r\n]*\)'
st = "Firstname Lastname (email1@place.edu) Firstname2 Lastname2 (email2@place.edu)"
''.join(re.findall(regexp_pattern, st))[1:-1].replace(")(", ",")