简体   繁体   中英

remove quotes and commas within a parathesis

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

I want get the quotes inside the brackets to be removed and to get an out

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

Your example input is way too small to create a credible pattern but under the assumption that you want to join your list elements when a closing brace is encountered, you can do something as simple as:

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)', '']

But to actually do a continuous join based on an open brace, and add a comma for each join you need to record the previous state for open braces and then wait for a closing one before joining everything together with a comma - something like:

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)', '']

Mind you, even this is prone to bad joins if there are multiple braces in the same element but the question is how deep are you willing to go to ensure every edge case is covered.

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

OUT PUT :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM