英文:
Strip function not working in a list in python
问题
with open(r"C:\filelocation") as f:
lines = f.readlines()
for i in lines:
i = i.strip()
i = i.split(",")
当我打印我的列表时,我得到以下结果:
['46', 'Celsius']
['42', 'Celsius']
['93', 'Fahrenheit']
我尝试过 i = i.strip()
,但对于我的列表不起作用。
英文:
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.
答案1
得分: 1
你现在的拥有的是一个列表的列表,也就是一个矩阵。你正试图使用一个for循环来去除每个列表的空白字符,但实际上你不能去除一个列表的空白字符。
你需要枚举遍历每一行中的每个项目,然后去除该项目的空白字符。
在你之前尝试去除的内容是:
> ['46', 'Celsius'] # 一个列表
而不是:
> 'Celsius' # 一个字符串
下面是重新编写的代码:
lines = []
with open('文件/位置') as f:
lines = f.readlines()
# 遍历矩阵中的每个列表/行。
for row in range(len(lines)):
# 遍历该列表中的每个项目
for column in range(len(lines[row])):
# 使用其行和列号去除每个项目的空白字符。
lines[row][column] = lines[row][column].strip()
print(lines)
结果:
> [['46', 'Celsius'], ['42', 'Celsius'], ['93', 'Fahrenheit']]
英文:
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']]
答案2
得分: -1
似乎您想在拆分后剥离标记。此外,您必须重新分配实际的列表元素,以使更改影响列表:
for i, line in enumerate(lines):
lines[i] = [token.strip() for token in line.split(",")]
请注意,line
只是一个循环变量,最初引用列表元素。将其分配给另一个值
line = ...
只会将此变量绑定到一个新对象。列表不会因此而改变。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论