如果string = 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
如何拆分此字符串?
答案 0 :(得分:0)
string.split()
你可以通过传递参数告诉Python你对split()
的看法。 see the docs for more functionality
split()
方法会为您留下list
,您可以在此情况下使用for loop或list comprehension来迭代访问每个项目。
在将问题(特定的)发布到SO之前,您应该始终查看Google和文档,以便获得最佳反馈。
编辑:
如果您只是尝试访问字符串b / w括号,则可以使用正则表达式或python' s find()
method
string = "Firstname Lastname (email1@place.edu) Firstname2 Lastname2 (email2@place.edu)"
stringlist = string.split()
email_addresses = [item[1:-1] for item in stringlist if "(" in item and ")" in item]
答案 1 :(得分:0)
使用正则表达式。
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(")(", ",")