Python字符串strip不去除换行符

0 投票
3 回答
3287 浏览
提问于 2025-04-18 09:37

我无法去掉空格和换行符。你们觉得可能出什么问题了?

    line_count = 0
    word_count = 0

    for fline in fh:
        line = repr(fline)
        line = line.strip()
        print line
        line_count += 1
        word_count += len(line.split())

    result['size'] = filesize
    result['line'] = line_count
    result['words'] = word_count

输出结果

'value of $input if it is\n'
' larger than or equal to ygjhg\n'
' that number. Otherwise assigns the value of \n'
' \n'
' '

3 个回答

1

根据其他人提到的内容,只需要把

    line = repr(fline)
    line = line.strip()

改成

    line = line.strip()
    line = repr(fline)

注意,你可能想用 .rstrip() 或者 .rstrip("\n") 来替代。

1

如果 fline 是一个字符串,那么用 repr 函数去处理它时,会把这个字符串放在引号里。这样:

foo\n

就变成了

"foo\n"

因为换行符不再在字符串的末尾,所以 strip 函数不会把它去掉。也许你可以考虑在没有必要的情况下不要使用 repr,或者在调用 strip 之后再使用它。

2

你的字符串被双引号包围是因为使用了 repr() 这个函数:

>>> x = 'hello\n'
>>> repr(x)
"'hello\\n'"
>>> repr(x).strip()
"'hello\\n'"
>>> 

这是你修改后的代码:

line_count = 0
word_count = 0

for fline in fh:
    line = repr(line.strip())
    print line
    line_count += 1
    word_count += len(line.split())

result['size'] = filesize
result['line'] = line_count
result['words'] = word_count

撰写回答