0

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.

4
  • 1
    [item.replace(')', '') for item in list] Commented Nov 25, 2022 at 3:44
  • 1
    Does this answer your question? Replace function in list of strings Commented Nov 25, 2022 at 3:45
  • OP upı should accept one of the answers. You asked for help. They helped... Commented Nov 25, 2022 at 10:10
  • [item.rstrip(")") for item in list] if you only want to eliminate the ")" at the end. And don't use list as variable name, you're overriding a builtin function. Commented Nov 25, 2022 at 15:45

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

5 Comments

str.replace is just as good as regex for a substitution this simple.
Yes, that might be fine, but perhaps the OP really only wants to target ) at the very end of each string.
That's not clear. The comment "# there is a parenthesis at the end" sort of implies it, but we don't know for sure.
Thanks for your response, I tried your solution but ")" is still there... maybe it's because I used re.findall() to get the value of the list from a HTML file....
Well my answer doesn't use re.findall and you are not using my answer.
1

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]

1 Comment

You don't need the if-else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.