Python: rstrip(' ') 并没有剥离 在我的清单中

问题描述 投票:0回答:1

我使用

.readLines()
将文件分成几行,但由于某种原因,在我创建列表并使用
line.rstrip('\n')
后,我的项目末尾仍然有
'\n'

lines = readFile.readlines()

for line in lines :
    line.rstrip('\n')

if lines[127] == "<th>FID</th>" :
    print(lines[127] + "is equal to <th>FID</th>")
else :
    print(lines[127] + "is not equal to <th>FID</th>")

我尝试使用

剥离
line.rstrip('\n')

但比较后仍然输出it is not equal.

python file
1个回答
0
投票

rstrip()
方法返回删除了尾随字符的新字符串,它不会就地修改原始字符串。您需要将结果分配回变量。试试这个:

lines = readFile.readlines()

for i in range(len(lines)):
    lines[i] = lines[i].rstrip('\n')

if lines[127] == "<th>FID</th>":
    print(lines[127] + " is equal to <th>FID</th>")
else:
    print(lines[127] + " is not equal to <th>FID</th>")

这将确保行列表中的每一行都删除其尾随换行符。

© www.soinside.com 2019 - 2024. All rights reserved.