Home > Net >  Remove ")" from cells in list if ")" exists
Remove ")" from cells in list if ")" exists

Time:11-25

Could you please tell me how can I remove ")" from strings in a list without converting the list to a string? Example:

Input:

list =[
 'ABDDDDC 1,000 IWJBCKNBCDVV',
 'BDISJBJ 2,000 DBFIAJDBDIAJ',
 'JDBISJB 5,000 AHSBIEFEWEFJ)', # there is a parenthesis at the end
 'CONDDDD 7,000 4DJVBDISJEVV)'] # there is a parenthesis at the end

Expected output:

list =[
 'ABDDDDC 1,000 IWJBCKNBCDVV',
 'BDISJBJ 2,000 DBFIAJDBDIAJ',
 'JDBISJB 5,000 AHSBIEFEWEFJ', # parenthesis is removed
 'CONDDDD 7,000 4DJVBDISJEVV'] # parenthesis is removed

I know how to do it by converting list to str like following:

a = str(list)
a = a.replace(")","")
print(a)

However, since I need convert it to a dataframe later... I want to keep it as list. Please let me know if you need any clarificaiton for my question. This is my first time to post a question.

CodePudding user response:

You may use a list comprehension here:

inp = ['ABDDDDC 1,000 IWJBCKNBCDVV', 'BDISJBJ 2,000 DBFIAJDBDIAJ', 'JDBISJB 5,000 AHSBIEFEWEFJ)', 'CONDDDD 7,000 4DJVBDISJEVV)']
output = [re.sub(r'\)$', '', x) for x in inp]
print(output)

This prints:

['ABDDDDC 1,000 IWJBCKNBCDVV',
 'BDISJBJ 2,000 DBFIAJDBDIAJ',
 'JDBISJB 5,000 AHSBIEFEWEFJ',
 'CONDDDD 7,000 4DJVBDISJEVV']

CodePudding user response:

This is the solution for that.

list =[
 'ABDDDDC 1,000 IWJBCKNBCDVV',
 'BDISJBJ 2,000 DBFIAJDBDIAJ',
 'JDBISJB 5,000 AHSBIEFEWEFJ)',
 'CONDDDD 7,000 4DJVBDISJEVV)']

list = [i.replace(')','') if ')' in i else i for i in list]
[print(x) for x in list]
  • Related