[Python] How to lstrip item from the list? [closed]

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I need to process item from the list and can not figure out why I'm failing, so many examples I've checked but in my case

    myList = [ str(x).lstrip() for x in myList]


    produces error

    AttributeError: 'list' object has no attribute 'lstrip'


    so I added str() but it still doesn't work.

    Here is my sample code, original myList is output after csv.reader(file) so list is defined exactly like in my excerpt, with square brackets around each item. What am I missing, is this some special kind of list (multidimensional or something)?

    My goal to remove leading spaces in the final list inside the loop. What is the difference between myList and myListX? They both class = list. For my case I can not change structure of myList.

    myList = [['item1 '], [' item2 xxxx'], ['item3 bb']] ## as csv.reader(file)
    print(myList); print(' item1..', myList[0], '.....df type:', type(myList))
    ### item1.. ['item1 '] .....df type: <class 'list'>

    myListX = ['item1X ',' item2X xxxx','item3X '] ## simple list, works fine.
    print(myListX); print(' itemX..', myListX[0], '.....df type:', type(myListX))

    myList = [ str(x).lstrip() for x in myList] #???? remove leading space

    c=1
    for tblx in myList:
    print( c,' ',tblx) ; c=c+1

    # wanted output:
    1 item1X
    2 item2X xxxx
    3 item3X

    #error when using x.lstrip without str on myList
    AttributeError: 'list' object has no attribute 'lstrip'

    Continue reading...

Compartilhe esta Página