Search code examples
pythonlistattributeerrorstrip

How to strip/remove certain characters from a list


I am currently trying to remove certain characters recursively from a python list.

I have a list:

lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']

I would like to remove the '_out' so that the list looks like this

>>lst1
['ZINC1.pdbqt', 'ZINC2.pdbqt', 'ZINC3.pdbqt']

My current code looks like this:

lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']    
for i in lst1:
        lst1.strip("_out")

But I get an error: AttributeError: 'list' object has no attribute 'strip'.


Solution

  • The following code achieves your goal. As already suggested by @drum, the replace method is useful for this.

    lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']
    lst2 = []
    for i in lst1:
        lst2.append( i.replace("_out", "") )
    
    print(lst2)