-3

I'd like to remove white spaces before & after each word in a list

with open(r"C:\filelocation") as f:
    lines = f.readlines()

for i in lines:
    i = i.strip()
    i= i.split(",")

When I print my list, I get the following

['46', 'Celsius  ']
['42', ' Celsius ']
['93', ' Fahrenheit ']

I tried i = i.strip() & it doesn't work for my list.

Ash S
  • 119
  • 5
  • 5
    Nowhere are you modifying your list, so your list doesn't change. Read a tutorial about list manipulation. Also make sure you provide a [mre]. – Julien Jun 19 '23 at 05:12

2 Answers2

1

What you have is a list of lists, aka a matrix. You are trying to strip each list using a for-loop, and you can't really strip a list.

You have to enumerate through each item in each row, THEN strip that item.

What you were trying to strip before was:

['46', 'Celsius'] # A list

Instead of:

'Celsius' # A string

The code is rewritten below:

lines = []
with open('file/location') as f:
    lines = f.readlines()

# Enumerates through each list/row in the matrix.
for row in range(len(lines)):
    # Enumerates through each item in that list
    for column in range(len(row)):
        # Strip each item using its row and column number.
        lines[row][column] = lines[row][column].strip()

print(lines)

Result:

[['46', 'Celsius'], ['42', 'Celsius'], ['93', 'Fahrenheit']]

Pork Lord
  • 164
  • 8
-1

Seems you want to strip the tokens after splitting. Also, you have to reassign the actual list element to make the changes affect the list:

for i, line in enumerate(lines):
    lines[i] = [token.strip() for token in line.split(",")]

Note that line is just a loop variable that is initially referencing the list element. Assigning it another value

line = ...

will simply bind this variable to a new object. The list does not get changed by that.

user2390182
  • 72,016
  • 6
  • 67
  • 89