删除括号内的引号和逗号

时间:2019-01-25 04:26:54

标签: python

x =['Jeff Bezos (chairman', ' president and CEO)', 'Werner Vogels (CTO)', '']
x ="".join(x)

我想删除括号内的引号并弄清楚

x =['Jeff Bezos (chairman,president and CEO)', 'Werner Vogels (CTO)', '']

2 个答案:

答案 0 :(得分:1)

您的示例输入太小而无法创建可信的模式,但是假设您想在遇到右括号时 join 您的列表元素,您可以执行以下操作: / p>

x = ['Jeff Bezos (chairman', ' president and CEO)', 'Werner Vogels (CTO)', '']
y = ['']
for element in x:
    y[-1] += element
    if element.endswith(')'):
        y.append('')
print(y)
# ['Jeff Bezos (chairman president and CEO)', 'Werner Vogels (CTO)', '']

但是实际上要基于一个大括号进行连续联接,并为每个联接添加一个逗号,您需要记录一下大括号的先前状态,然后等待一个闭合括号,然后再将所有内容与一个逗号联接在一起,例如:

x = ['Jeff Bezos (chairman', ' president and CEO)', 'Werner Vogels (CTO)', '']
y = []
cont = False
for element in x:
    if not cont:
        y.append('')
    y[-1] += (',' if cont else '') + element
    cont = element.rfind('(') > element.rfind(')')
print(y)
# ['Jeff Bezos (chairman, president and CEO)', 'Werner Vogels (CTO)', '']

请记住,即使在同一元素中有多个花括号,即使这样也容易产生不良联接,但问题是您愿意付出多大的努力才能确保覆盖所有边缘情况?

答案 1 :(得分:0)

import re

x = ['Jeff Bezos (chairman', ' president and CEO)', 'Werner Vogels (CTO)', '']

m=re.search('(\(.*?\))', str(x)) #finding the pattern starting with'('ending with')'
srt=m.group(0).replace("'", "")  # replacing single quotes within brackets.
x = re.sub('(\(.*?\))', srt, str(x),1)  #replacing the updated string in list
print '\n',x

输出:

['Jeff Bezos (chairman,  president and CEO)', 'Werner Vogels (CTO)', '']