python removing whitespace from string in a list

前端 未结 6 924
名媛妹妹
名媛妹妹 2021-01-18 10:24

I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing

6条回答
  •  感情败类
    2021-01-18 11:17

    So you have something like: [['a ', 'b', ' c'], [' d', 'e ']], and you want to generate [['a', 'b',' c'], ['d', 'e']]. You could do:

    mylist = [['a ', 'b', ' c'], ['  d', 'e  ']]
    mylist = [[x.strip() for x in y] for y in mylist]
    

    The use of indexes with lists is generally not necessary, and changing a list while iterating though it can have multiple bad side effects.

提交回复
热议问题