Search code examples
pythonstringlistwhitespacestrip

Removing spaces from multiple string items in a list in python


I have a list of string items in python:

positions = ['CF', 'LCMF', 'RW', 'AMF', 'LW', ' RAMF', ' LCMF', ' AMF', ' RB']

I want to remove the spaces from the items which contain spaces (e.g. ' RAMF').

I have tried this using the following code:

positions = [x.strip(' ') for x in positions]
# AttributeError: 'NoneType' object has no attribute 'strip'

player_positions = [x.text.strip(' ') for x in player_positions]
# AttributeError: 'str' object has no attribute 'text'

positions = map(str.strip, positions)
# <map at 0x7fde15d19a90>

How can I remove the spaces in any list item that contains a space here?


Solution

  • Solution (Edited):

    positions = ['CF', 'LCMF', 'RW', 'AMF', 'LW', ' RAMF', ' LCMF', ' AMF', ' RB']    
    positions = [x.strip(" ") for x in positions]